How to loop through elements of forms with JavaScript?

后端 未结 7 1299
無奈伤痛
無奈伤痛 2020-12-05 01:53

I have a form:

相关标签:
7条回答
  • 2020-12-05 02:19

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 02:21
    <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>
    
    0 讨论(0)
  • 2020-12-05 02:23

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

    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.getElementsByTagName provided you have given a name to yoy form

    DEMO with form Name

    0 讨论(0)
  • 2020-12-05 02:30

    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.

    0 讨论(0)
  • 2020-12-05 02:33

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

    Update: Array.from is a nicer alternative to spread Array.from(form.elements) it's slightly clearer behaviour.


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

    const forms = document.querySelectorAll('form');
    const form = forms[0];
    
    Array.from(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>

    0 讨论(0)
  • 2020-12-05 02:33

    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.
    }
    
    0 讨论(0)
提交回复
热议问题