Html 如何使用 JavaScript 遍历表单元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19978600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:19:11  来源:igfitidea点击:

How to loop through elements of forms with JavaScript?

javascripthtmlforms

提问by Please Delete me

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.

我更喜欢只使用纯 JavaScript,而不是 jQuery 或其他库。我还想将迭代限制为表单元素,而不是可以添加到表单中的任何其他元素。

回答by ZER0

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

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

<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:

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

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

And you will have in elementsjust 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:

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

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.

您基本上会保存一张支票。

回答by Lex

A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEachmethod is available. [...form.elements].forEach

现代 ES6 方法。使用您喜欢的任何方法选择表单。使用 spread 运算符将 HTMLFormControlsCollection 转换为 Array,则该forEach方法可用。[...form.elements].forEach



An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"

下面的示例迭代表单中的每个输入。您可以通过检查过滤掉某些输入类型input.type != "submit"

const forms = document.querySelectorAll('form');
const form = forms[0];

[...form.elements].forEach((input) => {
  console.log(input);
});
<div>
  <h1>Input Form Selection</h1>
  <form>
    <label>
      Foo
      <input type="text" placeholder="Foo" name="Foo" />
    </label>
    <label>
      Password
      <input type="password" placeholder="Password" />
    </label>
    <label>
      Foo
      <input type="text" placeholder="Bar" name="Bar" />
    </label>
    <span>Ts &amp; Cs</span>
    <input type="hidden" name="_id" />
    <input type="submit" name="_id" />
  </form>
</div>

回答by Satpal

You can use getElementsByTagNamefunction, it returns a HTMLCollection of elements with the given tag name.

您可以使用getElementsByTagName函数,它返回具有给定标记名称的元素的 HTMLCollection。

var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
    if(elements[i].value == "") {
        alert('empty');
        //Do something here
    }
}

DEMO

演示

You can also use document.myform.getElementsByTagNameprovided you have given a name to yoy form

如果document.myform.getElementsByTagName您已为 yoy 表单命名,您也可以使用

DEMO with form Name

带有表单名称的演示

回答by Ansar Ozden

You can iterate named fields somehow like this:

您可以像这样以某种方式迭代命名字段:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

或者,如果您只需要提交字段:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

回答by Mohamed Allal

Es5 forEach:

Es5 forEach:

Array.prototype.forEach.call(form.elements, function (inpt) {
       if(inpt.name === name) {
             inpt.parentNode.removeChild(inpt);
       }
});

Otherwise the lovely for:

否则可爱的:

var input;
for(var i = 0; i < form.elements.length; i++) {
     input = form.elements[i];

      // ok my nice work with input, also you have the index with i (in foreach too you can get the index as second parameter (foreach is a wrapper around for, that offer a function to be called at each iteration.
}

回答by Asad Zaman

<form id="yourFormName" >
<input type="text" value="" id="val1">
<input type="text" value="" id="val2">
<input type="text" value="" id="val3">
<button type="button" onclick="yourFunction()"> Check </button>
</form>
<script type="text/javascript">
function yourFunction()
{
  var elements = document.querySelectorAll("#yourFormName input[type=text]")
  console.log(elements);
  for (var i = 0; i<elements.length; i++ )
  {
    var check = document.getElementById(elements[i].id).value);
    console.log(check);
    // write your logic here
  }
}
</script>

回答by arvic.rivera

$(function() {
    $('form button').click(function() {
        var allowSubmit = true;
        $.each($('form input:text'), function(index, formField) {
            if($(formField).val().trim().length == 0) {
                alert('field is empty!');
                allowSubmit = false;
            }
        });
        return allowSubmit;
    });
});

DEMO

演示