1

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?

2 Answers 2

2

DEMO

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!");
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! I guess input[] returns a number which populates formVar array? I don't quite get how that works :S
formVar["input[]"] returns a collection of dom elements. In this case, those inputs with a name of "input[]"
2

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

Comments

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.