-2

this code works, and it alerts the variable every time.

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
while (whileLoop<112) {
    elements=document.getElementsByName('bid');
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    alert(blockerIds[whileLoop]);
    whileLoop++;
}

but I tried alerting it outside of the while statement, like this:

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
while (whileLoop<112) {
    elements=document.getElementsByName('bid');
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    whileLoop++;
}
alert(blockerIds);

but it only says "undefined". Does anyone know how I can use this variable outside of the while statement, or does it seem like it should work perfectly?

12
  • 3
    You should probably put the document.getElementsByName() call outside of your loop. Just sayin'... Commented Feb 21, 2014 at 22:00
  • How many elements are there named bid? What are their ids? Commented Feb 21, 2014 at 22:00
  • Also: if there aren't 112 of them, it will fail Commented Feb 21, 2014 at 22:00
  • there are 112 elements named bid, and there ids are "bid'x'_'x'" and x is always a number Commented Feb 21, 2014 at 22:01
  • 1
    use console.log() instead of alert, then you also see other error messages, when they occur. Commented Feb 21, 2014 at 22:01

2 Answers 2

0

JSFiddle: link. Fixed your code:

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
elements=document.getElementsByName('bid');
while ((elements.length >= 112 && whileLoop < 112) || (whileLoop < elements.length && elements.length <= 112)) {
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    whileLoop++;
}
alert(blockerIds);
Sign up to request clarification or add additional context in comments.

Comments

0

JS is an interpreted language, when it runs, it firstly search all the definitions of var, and give them an undefined value. Even if the var is claimed to have a actual value, it will still be given an undefined value until this line has been eventually executed.

2 Comments

I don't understand that.
var idNumber; var elements; var id; var blockerIds=[]; var whileLoop=0; elements="123"; while (whileLoop < 3) { // less than 112 elements=document.getElementsByName('bid'); id=elements[whileLoop].getAttribute('id'); blockerIds[whileLoop]=id; whileLoop++; } alert(blockerIds);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.