最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - Get Array of Inputs From Form - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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!");

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

发布评论

评论列表(0)

  1. 暂无评论