Reputation: 105
I am new to jQuery and mixing javascript with jQuery.
Clicking add_comment_bt
I send a get request to ajax.php and try to loop the data using the each statement:
(data has 2 arrays with 7 entries and it is multidimentional, you can see the data below)
c = 1;
$("#add_comment_bt").click(function () {
$.get('ajax.php', function (data) {
var arr = data;
jQuery.each(arr, function (i, val) {
var commentbox = document.createElement("div");
commentbox.id = 'commentbox' + c + '';
commentbox.className = 'comments';
container.appendChild(commentbox);
var commentBoxEach = document.getElementById('commentbox' + c + '');
var div = document.createElement("div");
div.id = 'comment' + c + '';
commentBoxEach.appendChild(div);
document.getElementById('comment' + c + '').innerHTML = "Comment: " + arr[0][i];
c++;
});
}, "json");
While looping I create two divs and put the data inside them. First 2 loops are created and work perfect but the rest of the result are not shown? Why does the loop stop?
Thanks
Here is my example JSON (I only put the first array):
[
["Green Apple", "Red Apple", "Green", "Apricot", "Banana", "Passionfruit", "Orange"],
["allen", "kate", "paul", "rose", "arnold", "ferry", "top"]
]
Here is the HTML for the container div:
<div><div id="container"></div><div id="commentDraftDiv"></div></div>
Here is the HTML result:
Upvotes: 1
Views: 155
Reputation: 782717
You're looping over the outer array, then using i
to index the first inner array. Since the outer array only has 2 elements, you only get the first two elements of the inner array.
If you just want the elements of the first inner array, you should loop over that.
var arr = data[0];
jQuery.each(arr, function (i, val) {
var commentbox = document.createElement("div");
commentbox.id = 'commentbox' + c;
commentbox.className = 'comments';
container.appendChild(commentbox);
var div = document.createElement("div");
div.id = 'comment' + c;
div.innerHTML = "Comment: " + val;
commentbox.appendChild(div);
c++;
});
There's also no need for
var commentBoxEach = document.getElementById('comment' + c);
That's the same ID you just gave to the element in commentbox
, so you can use that variable instead of searching for the element by ID.
And there's no need for + ''
in your concatenations. I see this all the time in newbie code, I've never understood why they do it.
Upvotes: 1
Reputation: 3712
Try this:
var arr = data;
for (var i in arr) {
var current = arr[i];
jQuery.each(current, function (j, val) {
var commentbox = document.createElement("div");
commentbox.id = 'commentbox' + c + '';
commentbox.className = 'comments';
container.appendChild(commentbox);
var commentBoxEach = document.getElementById('commentbox' + c + '');
var div = document.createElement("div");
div.id = 'comment' + c + '';
commentBoxEach.appendChild(div);
document.getElementById('comment' + c + '').innerHTML = "Comment: " + current[j];
c++;
});
}
Upvotes: 0