admin管理员组

文章数量:1399465

How can I get all controls and their values and selected state using JavaScript? It would be good to have an array having all the controls (like select and radio) in an array together with their selected state.

Is that somehow possible?

Thanks!

How can I get all controls and their values and selected state using JavaScript? It would be good to have an array having all the controls (like select and radio) in an array together with their selected state.

Is that somehow possible?

Thanks!

Share Improve this question asked Aug 27, 2012 at 12:11 user1540714user1540714 2,0894 gold badges21 silver badges23 bronze badges 2
  • What does your HTML look like? – João Silva Commented Aug 27, 2012 at 12:13
  • Too big to post, but its all in a form. – user1540714 Commented Aug 27, 2012 at 12:25
Add a ment  | 

2 Answers 2

Reset to default 5

All the controls of a form are available in the form.elements collection. You can then iterate over the collection and process them however you want.

e.g.

function processForm(form) {
  var control, controls = form.elements;
  for (var i = 0, iLen = controls.length; i < iLen; i++) {
    control = controls[i];

    // Do something with the control
    console.log(control.tagName + ':' + control.name + ' - ' + control.value);
  }
}
<form id="form0">
<fieldset><legend>The form</legend>
  <input name="inp0" value="foo"><br>
  <select name="sel0">
    <option value="opt0" selected>opt0
    <option value="opt1">opt1
    <option value="opt2">opt2
  </select><br>
  <input type="button" value="Process form" name="btn0" onclick="
       processForm(this.form);
      ">
  <input type="reset">
</fieldset>
</form>

<input name="outsideForm" form="form0" value="Over the fence">

If you do

myParentNode.querySelectorAll('input[type="checkbox"], input[type="radio"]');

You will get an array of HTMLElements that are <input>s with a type of checkbox or radio. You can then access their values with .value

本文标签: Getting all controls of a form in an array using JavaScriptStack Overflow