Why do I only receive a single alert from the following javascript? - javascript

This is a javascript function inside of a HTML tag, however - when I move the alert(currentalbum) below the for loop, the second alert does not run - only the first, why?
function populatetracks(albumvalue) {
var currentalbum = albumvalue;
alert(currentalbum); // #1
document.getElementById("TracksList").options.length = 0;
for(i = 0; albums[albumvalue].tracks.length - 1; i++) {
var s = document.getElementById('TracksList');
var opt = document.createElement('option');
opt.appendChild( document.createTextNode(albums[albumvalue].tracks[i].title));
opt.value = i;
s.appendChild(opt);
}
alert(currentalbum); // #2
}
'#1' does produce an alert, but '#2' doesn't.

As noted, not sure how your for loop is supposed to stop.
This has no evaluation in it, just an incrementor
for(i=0; albums[albumvalue].tracks.length -1; i++){
Maybe try this (might need to change '=' to '<=' )
for(i=0; i < albums[albumvalue].tracks.length -1; i++){

Related

For loop lasts infinitely javascript

I have a problem in my code:
var row = ["1","2","3","4","5"];
var column = ["1","2","3","4","5"];
var arrayLength = row.length;
var arrayLength2 = column.length;
for (var i = 0; i < arrayLength; i++) {
for (var e = 0; e < arrayLength2; e++) {
var samples = document.querySelectorAll('[data-row-id="'+row[i]+'"][data-column-id="'+column[e]+'"]');
for(var i = 0; i < samples.length; i++) {
var sample = samples[i];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}
}
}
When i run it, the cycle lasts infinitely and the console.log is called up a lots of times
Where is the error? Thanks!
The problem is that your inner-most loop uses the same i looping variable as your outer most loop and it's constantly changing i so that the outer loop never finishes.
Change the variable on your inner loop to a different identifier that you aren't already using in the same scope.
Youre using same loop i twice nested so it runs infinitely coz it always resets i in inner loop
use something else instead like k
for(var k = 0; k < samples.length; k++) {
var sample = samples[k];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}

Why wont my loop within a loop in Javascript work?

This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.
for(i = 0; i < questions.length-1; i++){
radios = document.getElementsByName(questions[i]);
for (var t = 0; length < radios.length; t++) {
if (radios[t].checked) {
var qResults = JSON.parse(localStorage["qResults"]);
num = radios[t].value;
checked = num.toString();
var temp = (id[0] + ";" + questions[i] + ";" + checked);
alert(temp);
qResults.push(temp);
localStorage["qResults"] = JSON.stringify(qResults);
}
}
alert("question finished");
}
Your inner loop is wrong. Change this:
for (var t = 0; length < radios.length; t++) {
to:
for (var t = 0; t < radios.length; t++) {
Side note: I would suggest that you read the local storage before the loops, and write it back after the loops, instead of doing it for every question.
In addition to Guffa's fix, I think it makes more sense if you can move var qResults and localStorage["qResults"] outside of the second for loop:
var qResults = JSON.parse(localStorage["qResults"]);
for loop I {
for loopII {}
}
localStorage["qResults"] = JSON.stringify(qResults);

Populating a select element with comma-separated values using for loop

I have a bunch of comma-separated values stored as strings in a JSON file. My aim is to split these values to populate a select element which is based on Selectize.js. Code (excerpt) looks as follows:
var options = {};
var attr_split = data.attributes['Attribute1'].split(",");
var options_key;
for (var i = 0; i < attr_split.length; i++) {
options_key = attr_split[i]
}
var options_values = {
value: options_key,
text: options_key,
}
if (options_key in options)
options_values = options[options_key];
options[options_key] = options_values;
$('#input').selectize({
options: options,
});
Although this seems to work, the output in the select element only shows the last iterations done by the for loop. As per here
and here, I've tried
for (var i = 0; i < attr_split.length; i++) {
var options_key += attr_split[i]
}
but this throws me undefined plus all concatenated strings without the separator as per the following example:
undefinedAttr1Attr2Attr3
When I simply test the loop using manual input of the array elements everything appears fine:
for (var i = 0; i < attr_split.length; i++) {
var options_key = attr_split[0] || attr_split[1] || attr_split[2]
}
But this is not the way to go, since the number of elements differs per string.
Any idea on what I'm doing wrong here? I have the feeling it's something quite straightforward :)
when you declare 'options_key' ,you are not initializing it.so its value is undefined .when you concatenate options_key += attr_split[i] .in first iteration options_key holds undefined.so only you are getting undefinedAttr1Attr2Attr3.
so declare and initialize options_key like.
var options_key="";
and in your loop
for (var i = 0; i < attr_split.length; i++)
{
options_key = attr_split[i]
}
Everytime you replace options_key with value of attr_split[i].so after the loop it will contain last element value.corrected code is
for (var i = 0; i < attr_split.length; i++)
{
options_key += attr_split[i]
}
Just change var options_key; to var options_key="";
The reason you are getting undefined is because you have not defined the variable properly.
Here is a working example
var attr_split = "1,2,3,4".split(",");
var options_key="";
for (var i = 0; i < attr_split.length; i++) {
options_key += attr_split[i]
}
alert(options_key);
var options_values = {
value: options_key,
text: options_key
}
alert(options_values);

Why does this for loop not run? jQuery

http://jsfiddle.net/leongaban/BvuT5/
Trying to get the 2nd alert to popup twice, however seems like the for loop isn't even running.
jQuery
var wireRequestorCard = function(jarjar) {
alert('1st alert');
var loop_num = 0;
for (var i = 0, length = jarjar.length; i < length; i++) {
loop_num = i;
alert('Where is this Alert? '+i);
}
alert('Closing Alert');
}
var jarjar = 2;
wireRequestorCard(jarjar);
You aren't passing an array or string to the function, which does not have a length property. Instead jarjar is a number.
jarjar is an integer.
it does not have a length property.
You just need to compare i to jarjar:
for (var i = 0; i < jarjar; i++) {
alert('Here is this Alert! '+i);
}
http://jsfiddle.net/daCrosby/BvuT5/5/

setting a variable to each element of an array

i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.

Categories