I am new to JS so struggling with this a bit.
$(function () {
$.ajax({
url: "some_url",
dataType: 'jsonp',
success: function (whatever) {
var allText = whatever.data._shared.text;
for (var i = 0; i < allText.length; i++) {
var text1 = allText[i];
var testHtml = "";
testHtml += "";
testHtml += "";
testHtml += "";
$("#text").append(testHtml);
document.write(allText.length);
}
}
});
});
In a variable I want the total count of objects returned (allText = whatever.data._shared.text).
I tested out by using document.write(allText.length); and I am getting the right number but the result looks like this:
2020202020202020202020202020202020202020
So it appears to be repeating. How can I get the actual value, which is 20, inside a variable only once instead of it repeating?
You call document.write(allText.length);
inside the for loop, so one time per iteration (so you write it 20 times). Try to call it outside the for loop:
var allText = whatever.data._shared.text;
for (var i = 0; i < allText.length; i++) {
var text1 = allText[i];
var testHtml = "";
testHtml += "";
testHtml += "";
testHtml += "";
$("#text").append(testHtml);
}
document.write(allText.length);
Also try to use your browser's debugger (go step by step) to understand what happened.