Reputation: 379
I'm dynamically adding text fields (maximum 32) into my page and I need to go through all of them and check, if all of them are empty I will display a warning message! I don't want to use document.getElementsByTagName('input') cause I have others text files on the page apart of dynamic ones!
I don't know why when I'm using this code below it doesn't allow me to get out from FOR loop and print alert('Test') and print warning?
Could anyone help me to sort this problem! Thanks!
var counter=0
for(var i = 1; i <= 32; i++){
var e = document.getElementById('mytextfieldid'+i).value;
if(e==''){}
else{counter++;}
}
alert('Test');
if(counter==0){DisplayWarning();}
Upvotes: 0
Views: 418
Reputation: 1015
If you want to check that ALL elements are blank you might want to try using a flag. If any values are hit change the flag and break out of the loop.
NOTE: Breaks tend to make things a little harder to follow.
var empty = true;
for(var i = 1; i <= 32; i++){
var e = document.getElementById('mytextfieldid'+i);
if(e && e.value !=''){
console.log(e);
empty = false;
break;
}
}
alert('Test');
if(empty){DisplayWarning();}
Upvotes: 1
Reputation: 53
If the number of elements is variable, why is the loop always going to 32? I would have it be a variable that matches the number of the last dynamically added field.
Upvotes: 0
Reputation: 1891
When writing
document.getElementById('mytextfieldid'+i).value
you assume document.getElementById('mytextfieldid'+i)
exists. If not it will raise an error and stop code execution.
You need to test the element before accessing the value.
var element = document.getElementById('mytextfieldid'+i);
if(element){
// update your counter...
}
Upvotes: 2