How to loop through all elements of a form jQuery

前端 未结 9 2067
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:57

    Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.

    var criteria = $(this).find('input,select').filter(function () {
        return ((!!this.value) && (!!this.name));
    }).serializeArray();
    
    var formData = JSON.stringify(criteria);
    

    serializeArray() will produce an array of names and values

    0: {name: "OwnLast", value: "Bird"}
    1: {name: "OwnFirst", value: "Bob"}
    2: {name: "OutBldg[]", value: "PDG"}
    3: {name: "OutBldg[]", value: "PDA"}

    var criteria = $(this).find('input,select').filter(function () {
        return ((!!this.value) && (!!this.name));
    }).serialize();
    

    serialize() creates a text string in standard URL-encoded notation

    "OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"

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

    As taken from the #jquery Freenode IRC channel:

    $.each($(form).serializeArray(), function(_, field) { /* use field.name, field.value */ });
    

    Thanks to @Cork on the channel.

    0 讨论(0)
  • 2020-12-14 01:02
    $('#new_user_form').find('input').each(function(){
       //your code here
    });
    
    0 讨论(0)
提交回复
热议问题