Hey I'm trying to get list of all input fields in a HTML form, but I get following error(in Firebug):
ReferenceError: assignment to undeclared variable i
for (i=0 ; i<inputs.length; i++)
I don't understant how is "i" undeclared because that is that first part of "for" does. This is my formula
function listinputs()
{
var form = document.getElementById("wholeform");
var inputs = form.childNodes;
for (i=0 ; i<inputs.length; i++)
{
var string=string + inputs[i].nodeName + "<br>";
var here = document.getElementsByTagName("p");
here.innerHTML(string);
}
}
for (var i=0; i<inputs.length; i++)
You need to declare it with var
As T.J said in his answer, since you're using strict mode, an implicit global is not made. That's why an error is thrown.
It's not saying i
is unassigned, it's saying it's undeclared. The code never declares an i
variable, but then tries to assign a value to it (in the initialization part of the for
loop). Apparently you're using strict mode (good!), and so the engine is giving you an error rather than creating an implicit global.
Declare i
using var
in the function, e.g.:
function listinputs()
{
var form = document.getElementById("wholeform");
var inputs = form.childNodes;
var i; // <=================================== Here
for (i=0 ; i<inputs.length; i++)
{
string=string + inputs[i].nodeName + "<br>";
here = document.getElementsByTagName("p");
here.innerHTML(string);
}
}
Side note: In ES6, when it arrives, if you want you can use let
and scope i
to the for
statement only. But for now, use var
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With