Using a for loop with JSON - javascript

Should be very simple, but I only get Jimmy cricket output and I'm expecting all the names in li tags. Thanks for any help.
<ul id="members"></ul>
<script>
var teammembers = [
{"name":"John Doe", "profile":"/img/profile/user1.jpg", "position":"President", "email":"email#example.com", "phone":"242-abcd"},
{"name":"James Bond", "profile":"/img/profile/user2.jpg", "position":"Vice President", "email":"007#example.com", "phone":"242-0007"},
{"name":"Jimmy Cricket", "profile":"/img/profile/user3.jpg", "position":"Vice Cricket", "email":"cricket#example.com", "phone":"242-wxyz"}
];
for (var i = 0; i < teammembers.length; i++) {
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
}
</script>

The = sign here is replacing the innerHTML on each iteration. Hence you see the last value of the array here.
Convert it to a +=. Like this,
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"
+= will append it.

You need to append to the innerHTML, rather than set it. Instead of this:
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
use this (the change is from using = to using +=):
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"

Related

Concat string dynamically Javascript

I should concatenate an HTML string (i.e. "<div>HTML string</div>") to compose dinamically a description for Guider-JS.
I tried to do that using concat method but doesn't work.
var str = "<div><p>first test:</p><ul>";
for(var i=0; i<list.length;i++){
str+=("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("one " + str);
Otherwise, if I use += operator works well.
var str = "<div><p>second test:</p><ul>";
for(var i=0; i<list.length;i++){
str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("two " + str);
I have made a fiddle for explain better the case.
Sorry for my question, maybe is trivial but i don't understand why this happen
String#concat returns the new string with the concatenated values, so you want to assign that result to str: str = str.concat(...
Note that if you're using concat, you don't need + anymore:
str = str.concat("<li class='pointer' onclick=alert('hello')>", list[i], "</li>");
// -----------------------------------------------------------^^-------^^
Check the updated fiddle
make it
str = str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");

Trouble passing entire two dimensional array as parameters in JavaScript/jQuery

I am trying to generate divs around each of the elements of a two dimensional array using the methods below. So far the code only outputs the last 3 elements in the array (the 3 elements of third nested array). I am passing the array elements as parameters using .apply. How could I modify this to output each element of the array catArray in order? And why would it only pass the last 3 as it is? Any advice would be appreciated, I am trying to understand this better. I have spent hours on this, hopefully someone can help.
Here is a codepen:
http://codepen.io/anon/pen/kzEdK
function cats(catName, catFur, catEyes) {
$("#row").html('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();
You probably want something like:
function cats(catName, catFur, catEyes) {
// note the difference (append() instead of html())
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
function catGenerator() {
$("#row").html(""); // in case you wish to call catGenerator() multiple times, clear the row before appending to it
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
It shows only the last 3 elements because $("#row").html("...") overwrites the contents of #row three times and the value set in the last iteration remains visible. I fixed that by replacing html() with append(), which does what you want.
The problem is that you have $("#row").html() which will replace the markup within the div tag after each iteration. Consider using $("#row").append()
function cats(catName, catFur, catEyes) {
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();

store ID from listview in localStorage

I've a listview created by a loop:
for(var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" id=\"submitID\" >" +
"<h2>"+garage.location+"</h2>" +
"<p><b>"+garage.description+"</b></p>" +
"<p>"+garage.address+"</p>" +
"</a></li>" +
"</ul><br>"
);
$("#submitID").click(function() {
localStorage.setItem("garageID",garage.ID);
$.mobile.changePage("#resP");
});
}
Now the user can click on a listview item and the ID from this item should be stored in the localStorage.
Problem: It first creates the complete listview with all items. If I click now on item#2 from the list, I get the ID from the last item.
the submit function is being overwritten with every iteration of the loop, and every single #submitID is only calling that function. So, of course it will only pull up the last one in the list.
Also, the code is generating all items within data.length, so you'll need to alter that if you don't want everything in the list.
Here's a fix to the first part (assuming no styling is assigned to #submitID):
for(var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" id=\"submitID-" + i + "\" >" +
"<h2>"+garage.location+"</h2>" +
"<p><b>"+garage.description+"</b></p>" +
"<p>"+garage.address+"</p>" +
"</a></li>" +
"</ul><br>"
);
$("#submitID-" + i).click(function() {
localStorage.setItem("garageID",garage.ID);
$.mobile.changePage("#resP");
});
}
I think the problem was that the method was trying to reference garage when there wasn't a reference, or something like that. And you should have made the click method for a specific ID, because it just kept getting overridden each time. I fixed it for you by making it one click method for a class, but the ID of each garage element is its actual garage ID.
http://jsfiddle.net/Fq3TF/1/
Also, just a tip, if you're constructing a string which is going to be inserted into an HTML document, you can use an apostrophe instead of a quote to avoid escaping. e.g. "<a class='submitID'>Hello World</a>".
Here is my take on the problem. I use a attribute to save the id in the a element. The registering of the click handler has been moved outside the loop.
var data = [
{
id: "id1",
location: "location1",
description: "description1",
address: "address1"
},
{
id: "id2",
location: "location2",
description: "description2",
address: "address2"
}
];
for (var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" class=\"submitClass\" garageid=\"" + garage.id + "\">" +
"<h2>" + garage.location + "</h2>" +
"<p><b>" + garage.description + "</b></p>" +
"<p>" + garage.address + "</p>" +
"</a></li>" +
"</ul><br>"
);
}
$(".submitClass").click(function(e) {
e.stopPropagation();
alert($(this).attr("garageid"));
/*localStorage.setItem("garageID", garage.ID);
$.mobile.changePage("#resP");*/
});

change the order js inserts the text into the html

I need to change the where the js inserts the text into the html currently it is always putting at the end and I need it to insert it at the start and push the others down. That is, if it inserts
<li>1</li>, <li>2</li>, <li>3</li>
it will keep it in that order I need the last one to always be listed first like
<li>3</li>, <li>2</li>, <li>1</li>
Here is the html
<div class="data">
<div class="stackleft" id="p1_stack"></div>
<div class="stackright" id="p2_stack"></div>
</div>
Here is the JavaScript
function drawStack(isFinal) {
var stackLength = Oscore[currentPlayer].stack.length;
var temp = "";
var tot = 0;
for (var i = 0; i < stackLength; i++) {
var val = Oscore[currentPlayer].stack[i];
temp += "<li>" + val + "</li>";
tot += val;
}
//if(!isFinal){
//temp = '<div class="workingScore">'+scoreTemp+'</div><br>' + temp;
//}
var writeSore = document.form1.game.value - tot;
writeit(writeSore, currentPlayer + "_score");
writeit(temp, currentPlayer + "_stack");
}
Try to loop backward:
for (var i = stackLength; i--; ) {
var val = Oscore[currentPlayer].stack[i];
temp += "<li>" + val + "</li>";
tot += val;
}
How about this:
temp = "<li>" + val + "</li>" + temp;
You were missing a quote in the code shown too (now fixed by someone's edit), probably wouldn't have worked at all as written originally.
EDIT: I think I like the loop backward approach better, but it's up to you what you think is clearest.
use prepend() from JQuery.....

Using a for loop with JSON object/array elements?

I'm trying to create a for() loop with JSON data that's already been decoded, the problem is adding my loop variable (in this case i), to the end of the element that I'm referencing.
For example, my JSON structure, dumped:
{
"url": "http://www.example.com",
"rid": 1,
"rname": "Apple iPhone 4 Rotation",
"rmin": 90,
"rmax": 150,
"blank": 0,
"geo_country_0": "GB",
"geo_url_0": "http://en",
"geo_country_1": "FR",
"geo_url_1": "http://fr",
"geo_country_2": "ES",
"geo_url_2": "http://es"
}
In the case of geo_country_ and and geo_url_ I need to append a number, in this case the loop variable.
My actual for loop, for a better understanding:
for(i = 1; i < count; i++) {
$('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data.geo_url_i+ '"/></div>');
$('select[name="g_country['+i+']"').find('option[value="' + data.geo_country_i+ '"]').attr('selected','selected');
}
So far I've tried:
Encasing the the i like [i].
Escaping it like \i. (This was probably a stupid idea).
Adding a pre-fixing + like, + data.geo_country + i +.
What do I need to do to have i interpreted properly?
Any help would be greatly appreciated!
In JavaScript, you may address an object's properties in two ways:
var value = myobject.myproperty;
var value2 = myobject['myproperty'];
Using this knowledge, you can rewrite your code as follows:
for(i = 1; i < count; i++) {
$('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data['geo_url_' + i] + '"/></div>');
$('select[name="g_country['+i+']"').find('option[value="' + data['geo_country_' + i] + '"]').attr('selected','selected');
}
Access it like
data['geo_country_' + i]
And you should have no issues

Categories