I have a javascript array of object that looks like this:
"partners":[{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}]
I would like to output the value of each array's key using the underscore library. So for each object, I'd like to output something that looks like this:
<h1>Username Value</h1><img src="profileImg Value here" />
A bit confused about your "source", but I think you're just trying to do this:
_.each(partners, function(p) { document.write('<h1>' + p.username + '</h1>\
<img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write
Is this the result you're looking for?
this would only be applicable if your source looked more like:
var partners = [{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}];
EDIT:
var someBiggerObject = {
partners: [
{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}
]
};
_.each(someBiggerObject.partners, function(p) { document.write('<h1>' + p.username + '</h1>\
<img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write
The right way to do this is _.template
Example
If your structure is like this:
var list = {"partners":[
{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}
]};
You can create the repeated item template (note type="text/html")
<script type="text/html" id="userItemTemplate">
<h1><%= username %></h1><img src='<%= profileImg %>' />
</script>
and put each item into the template via a loop
var uIT = $("#userItemTemplate").html();
_.each(list.partners,function(user){
$("#target").append(_.template(uIT,user));
});
OR
put the loop into your template
<script type="text/html" id="userTemplate">
<% _.each(partners,function(user,key,list){ %>
<h1><%= user.username %></h1><img src='<%= user.profileImg %>' />
<% }); %>
</script>
then push the whole array in
var uT = $("#userTemplate").html();
$("#target2").html(_.template(uT,list));
Note that I am using lodash instead of underscore. It's compatible for the most part, but I prefer lodash because the benchmarks are faster and the library is maintained well.
Related
I want to change the HTML content of my webpage from within a javascript function. My HTML looks like this:
<div class="chartInfo">
<p id="last_updated">Hello</p>
</div>
My Javascript function is a QueryResponse to a GoogleCharts query. It looks like this:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function function_1() {
var queryString = encodeURIComponent('SELECT AA, AB');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dXP9yGEzNlmRxwCr2kyMM9CcS5hloIxKvef0RSa10/gviz/tq?gid=559927965&headers=1&tq=' + queryString);
query.send(function_2);
};
function function_2(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var data = response.getDataTable();
var t = (data.getvalue(0,0));
var latest_time = t.getDate()
document.getElementById("last_updated").innerHTML = "Last updated: " + latest_time;
};
</script>
Currently the webpage is showing "Hello" rather than "Last Updated: " + latest_time as I want it to.
I think it may be a problem of scope - when I write scripts out underneath I can change it from "Hello" to another string using document.getElementById, but then I can't access the variable latest_time which is within function_2.
Thanks in advance for any help!
Change dom.innerHTML to dom.textContent for changing text of it
So i'm back here again trying to figure out how to use HTML correct and can't get it to work correctly after been trying many hours with this.
Anyways, i'm trying to make so the picture and youtube trailer should be shown in the HTML and what I search for is something like this.
Right now im searching to make something like the picture but to get picture to be shown and a player with the trailer
so basically I want it to look similar like picture number one and I have come so far:
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function callAjax(input)
{
var url = "http://localhost:1337/search/" + input;
$.ajax({
type:'GET',
url: url,
success: function(data)
{
console.log('SUCCESS');
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html("Poster: " + data.poster);
},
error: function(request, status, err)
{
console.log('ERROR');
}
});
}
$(document).ready(function(){
$('#get-json').on('click', function(e){
e.preventDefault();
var input = $('#data').val().trim();
callAjax(input);
});
});
</script>
<body>
<center>
<div>
<input type="text" id="data" name="data" size="15" maxlength="120" />
<button type="submit" value="search" id="get-json">Search</button>
</div>
</center>
<section>
<div id="json-output"></div>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<div id="poster" img src="data.poster" style="width:104px;height:142px;"></div>
</section>
</body>
</html>
Also forgot to say that i'm very new at this, never done HTML really before and been trying to figure out this for a while without a result :(
You need to create placeholders for your JSON elements. At first write without that JSON a sample of HTML page that will look like you want. That page should have elements (for example div) for title, release and so on. Those elements should have its class or ids to be addressed (as it is already with <div id="json-output">)
You do not have to stringify your JSON. It is better to work JSON, since you can address its elements. For example, to set value into specific placeholder element you can use:
$('#title').html(data.title);
$('#relese').html(data.release);
$('#vote').html(data.vote);
JSON.stringify will return the contents of a JSON object as a string. It will not parse your JSON object and return HTML.
You can create a simple list like this:
function(data){
var $list = $('<ul>');
$list.append('<li>Title: ' + data.title + '</li>');
$list.append('<li>Release: ' + data.release + '</li>');
$list.append('<li>Vote: ' + data.vote + '</li>');
$list.append('<li>Overview: ' + data.overview + '</li>');
$('#json-output').html($list);
}
I have a json.json file like this
{"name1":"Hallo","name2":"Defy","name3":"Carm","name4":"Disney"}
And this script im using to read the file
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
$.each(person, function(key, value)
{document.write(key+"= "+value+"<br />");
});
});
});
</script>
This script is made to poin out all of the data but i need only "name3" value to be stored to +value+
How to do that?
You dont need to iterate then:
$.getJSON("json.json", function(person){
document.write("name3=" person.name3);
});
I'd probably stray away from document.write and append to a container.
<div id="test"></div>
$.getJSON("json.json", function(person) {
$("#test").append("<span> name3= " + person.name3 + </span>");
});
$.getJSON provides the JavaScript object that is represented by the JSON it retrieves.
To access the name3 property of the object, as with any JavaScript Object, you can simply do:
$.getJSON("json.json", function(person){
// do whatever you want with person.name3...
console.log(person.name3);
}
To access to the property you just have to use " . ", so to get the name3 you have to do value.name3
There's no no need to use a foreach if you only have 1 item
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
document.write(key + " = " + value.name3 + "<br />");
});
});
</script>
I have a string contaning some html markup, like this:
var html = "<div>
<img src="http://test.com/image1.png" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>";
i want to replace all urls inside src="..."
It is ok if i do html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, "SOME_URL");
then all src="..." become src="SOME_URL"
But now i want to replace each match with a different string, taken from an array, but i'm having trouble with this.
I think i have to use a function for the replacement, but not sure how to implement it.
Something like:
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){ //what do i do here??? });
So, if i have:
var arr = [];
arr['http://test.com/image1.jpg']='file1';
arr['http://test.com/test.jpg']='file3';
the html string from above will become:
"<div>
<img src="file1" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>"
Note that 'http://text.com/image2.jpg' is not a key of the array, so it does not gets replaced.
Any help appreciated, thank you in advance.
var html = '<div><img src="http://test.com/image1.jpg" />...</div>';
var arr = {
'http://test.com/image1.jpg' : 'file1',
'http://test.com/test.jpg' : 'file3'
}
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){
return ' src="' + (arr[$1] || $1) + '"';
});
console.log(html) returns
"<div><img src="file1" /><h1>SOME TEXT</h1><img src="http://text.com/image2.jpg" /></div>"
I'd forget about regex in this case, if you have an array containing all urls and their individual replacements in an object, why not do something like:
for (i in replaceObj)
{
html = html.split(i).join(replaceObj[i]);
}
tried it in console:
html = '<div><img src="imgs/img.jpg"/></div>';
replaceObj = {};
replaceObj['imgs/img.jpg'] = 'file';
for(i in test){html = html.split(i).join(replaceObj[i])};
output: <div><img src="file"/></div>. You could split on src="'+i'"' and concat. the same when joining to be on the safe side... but bottom line: keep it simple, whenever you can
This question already has answers here:
How to add a list of images to the document from an array of URLs?
(2 answers)
Closed 7 years ago.
I am trying to display six images from a javascript array. Running the code below I get no results it simply seems to be not working. I have no idea where my fault is.
Here is the javascript code:
var backgroundImage = new Array();
backgroundImage[0] = "images/colors-wallpaper.jpg";
backgroundImage[1] = "images/florida-birds.jpg";
backgroundImage[2] = "images/focus-on-life.jpg";
backgroundImage[3] = "images/set-into-life.jpg";
backgroundImage[4] = "images/dandelion.jpg";
backgroundImage[5] = "images/flowers.jpg";
backgroundImage[5] = "images/flowers.jpg";
function displayAllImages() {
// Here has to be some error!!! //
for (i=0;i<backgroundImage.length;i++) {
document.write("<li><img src='" + backgroundImage[i] + "' width="160" height="120"/><span>" + backgroundImage[i] + "</span></li>");
}
}
And that's my html code:
<html>
<head>
<script type="text/javaScript" src="changebackground.js"></script>
</head>
<body>
<div id="container">
<div class="backgoundImage">
<ul>
<script>displayAllImages();</script>
</ul>
</div>
</div>
</body>
</html>
Change
width="160" height="120"
to
width='160' height='120'
In
document.write("<li><img src='" + backgroundImage[i] + "' width="160" height="120"/><span>" + backgroundImage[i] + "</span></li>");
You are using wrong quotation marks
Your last array item key should be 6 (also I reckon as same value it's a copy/paste error) and I would strongly recommend against using document.write for such thing. Check link to see what I think you want to achieve but done in a slightly cleaner way (demo using jQuery just for the dom ready handling)
http://jsfiddle.net/UnFUB/
You need to escape your double quotes, see below:
document.write("<li><img src='" + backgroundImage[i] + "' width=\"160\" height=\"120\"/><span>" + backgroundImage[i] + "</span></li>");
document.write("<li><img src='" + backgroundImage[i] + "' width='160' height='120'/><span>" + backgroundImage[i] + "</span></li>");
You have a mistake in quotes. But better do not use document.write
The beeter way is to create an element in memory, and then put it in this block. How it looks on jQuery