I'm trying to make a universal "Check Empty" javascript function. What I figured I would do was onsubmit get the number of input
boxes in the form and take it's length like so:
I did pass the form name into the function via this.name
and called it formVar
var len = formVar.input[].value;
Then I would use that variable as a limit to a loop so I could check each one and see if it was empty. What's the problem with the above code snippet? Is there a way to get a number of inputs in a form?
I'm trying to make a universal "Check Empty" javascript function. What I figured I would do was onsubmit get the number of input
boxes in the form and take it's length like so:
I did pass the form name into the function via this.name
and called it formVar
var len = formVar.input[].value;
Then I would use that variable as a limit to a loop so I could check each one and see if it was empty. What's the problem with the above code snippet? Is there a way to get a number of inputs in a form?
Share Improve this question asked Jan 12, 2012 at 5:41 Howdy_McGeeHowdy_McGee 10.7k30 gold badges116 silver badges191 bronze badges2 Answers
Reset to default 2DEMO
input[]
isn't a valid identifier in JavaScript, so you'll need to access these inputs as a string index on your form:
var allInputs = formVar["input[]"];
var len = allInputs.length;
var anyChecked = false;
for (var i = 0; i < len; i++)
if (allInputs[i].checked){
anyChecked = true;
break;
}
if (!anyChecked)
alert("all checkboxes are empty!");
You can use the following to figure out the number of input elements in your form:
document.forms['search'].getElementsByTagName('input').length
this assumes you have a form named search. or you can use your formVar
to replace dcoument.forms['search']
part