How to loop through all elements of a form jQuery

前端 未结 9 2066
Happy的楠姐
Happy的楠姐 2020-12-14 00:11

I was just wondering what the best way of looping through all the child elements of a form would be? My form contains both input and select elements.

At the moment I

相关标签:
9条回答
  • 2020-12-14 00:37

    What happens, if you do this way:-

    $('#new_user_form input, #new_user_form select').each(function(key, value) {
    

    Refer LIVE DEMO

    0 讨论(0)
  • 2020-12-14 00:48

    From the jQuery :input selector page:

    Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

    This is the best choice.

    $('#new_user_form *').filter(':input').each(function(){
        //your code here
    });
    
    0 讨论(0)
  • 2020-12-14 00:48

    I'm using:

    $($('form').prop('elements')).each(function(){
        console.info(this)
    });
    

    It Seems ugly, but to me it is still the better way to get all the elements with jQuery.

    0 讨论(0)
  • 2020-12-14 00:50

    $('#new_user_form :input') should be your way forward. Note the omission of the > selector. A valid HTML form wouldn't allow for a input tag being a direct child of a form tag.

    0 讨论(0)
  • 2020-12-14 00:51

    pure JavaScript is not that difficult:

    for(var i=0; i < form.elements.length; i++){
        var e = form.elements[i];
        console.log(e.name+"="+e.value);
    }
    

    Note: because form.elements is a object for-in loop does not work as expected.

    Answer found here (by Chris Pietschmann), documented here (W3S).

    0 讨论(0)
  • 2020-12-14 00:53

    I have found this simple jquery snippet, to be handy for choosing just the type of selectors I want to work with:


    $("select, input").each(function(){
         // do some stuff with the element
    });
    
    0 讨论(0)
提交回复
热议问题