How to loop through all elements of a form jQuery

前端 未结 9 2065
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"

提交回复
热议问题