如何使用JavaScript循环表单元素? [英] How to loop through elements of forms with JavaScript?

查看:121
本文介绍了如何使用JavaScript循环表单元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单:

 < form method =POSTaction =submit.php> 
< input type =textvalue =1>
< input type =textvalue =2>
< input type =textvalue =3>
< input type =textvalue =4>
< button type =submit>提交< / button>
< / form>

如何循环表单中的输入元素(为了对它们执行一些验证) ?



我宁愿只使用纯JavaScript,而不使用jQuery或其他库。我还想限制迭代形式的元素,而不是可能添加到表单中的任何其他元素。 解决方案

您需要获取表单的引用,然后可以迭代元素集合。因此,假设例如:

 < form method =POSTaction =submit.phpid =my-形式> 
..etc ..
< / form>

您会看到类似的内容:

  var elements = document.getElementById(my-form)。elements; 

for(var i = 0,element; element = elements [i ++];){
if(element.type ===text&& element.value == =)
console.log(这是一个空的文本框)
}

请注意,在支持querySelectorAll的浏览器中,您也可以执行类似以下操作:

  var elements = document.querySelectorAll( #my-form input [type = text] [value =''])

元素中只有具有空值属性的元素。但是请注意,如果用户更改了该值,则该属性将保持不变,因此此代码仅用于按属性过滤而不由对象的属性过滤。当然,你也可以混合两种解决方案:

  var elements = document.querySelectorAll(#my-form input [type = text])

for(var i = 0,element; element = elements [i ++];){
if(element.value ===)
console.log(它是一个空的文本框)
}

检查。


I have a form:

<form method="POST" action="submit.php">
    <input type="text" value="1">
    <input type="text" value="2">
    <input type="text" value="3">
    <input type="text" value="4">
    <button type="submit">Submit</button>
</form>

How can I loop over the input elements in the form (in order to perform some validation on them)?

I'd prefer to use only pure JavaScript, not jQuery or another library. I'd also like to limit the iteration to form elements, not any other elements which may be added to the form.

解决方案

You need to get a reference of your form, and after that you can iterate the elements collection. So, assuming for instance:

<form method="POST" action="submit.php" id="my-form">
  ..etc..
</form>

You will have something like:

var elements = document.getElementById("my-form").elements;

for (var i = 0, element; element = elements[i++];) {
    if (element.type === "text" && element.value === "")
        console.log("it's an empty textfield")
}

Notice that in browser that would support querySelectorAll you can also do something like:

var elements = document.querySelectorAll("#my-form input[type=text][value='']")

And you will have in elements just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:

var elements = document.querySelectorAll("#my-form input[type=text]")

for (var i = 0, element; element = elements[i++];) {
    if (element.value === "")
        console.log("it's an empty textfield")
}

You will basically save one check.

这篇关于如何使用JavaScript循环表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆