How to loop through elements of forms with JavaScript?

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

I have a form:

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
    });

    Input Form Selection

    Ts & Cs

提交回复
热议问题