0

i have a form which have 39 text input fields. their ids are input1, input2 ... input39. what i want to do is if any of them doesnt contain any value then my script will delete it which is no problem. the problem is when i check the values of those text fields one by one it works fine but when i use a loop it shows error.so i ran a very simple test in the firebug console..

var i=1;
var asd="";

asd='input' + i;
var test=document.getElementById(asd).value;
asd="";
test;

if i run the above code in the firebug console then it works fine, shows the value of 1st textbox. but..

var i=1;
var asd="";

for(i=1;i<39;i++)
{
    asd='input' + i;
    var test=document.getElementById(asd).value;
    asd="";
    test;
}

if i run this code then i get TypeError: document.getElementById(...) is null

any idea why is this happening?? all the textboxes default value is "" (empty string)..

2 Answers2

1

Somewhere in your loop you are calling an ID that does not exist. Make sure your input IDs are what you think they are and make sure your loop ends at the appropriate time. For example if you have IDs to input38 make sure your loop doesn't go to input39. And make sure you have IDs for each iteration of the loop (ex. input1 - 38).

pizzarob
  • 11,711
  • 6
  • 48
  • 69
-1

First of all you have to set the limit of the for loop to 40 or <= 39 to include the 39th element.

Try this:

for (var i=1;i<=39;i++) {
    var asd = 'input' + i;
    var test = document.getElementById(asd).value;
    test;
}