jQuery serializeArray() key value pairs

前端 未结 10 1740
無奈伤痛
無奈伤痛 2020-11-28 06:25

I\'m having a bit of trouble serializing a form

相关标签:
10条回答
  • 2020-11-28 06:45

    To get only form inputs where has a value...

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

    criteria: {name: "LastName", value: "smith"}

    0 讨论(0)
  • 2020-11-28 06:52
    var result = { };
    $.each($('form').serializeArray(), function() {
        result[this.name] = this.value;
    });
    
    // at this stage the result object will look as expected so you could use it
    alert('name1 = ' + result.name1 + ', name2 = ' + result.name2);
    

    Live demo.

    0 讨论(0)
  • 2020-11-28 06:53

    Here is my solution which supports radio buttons and multi-select.

    var data = $('#my_form').serializeArray().reduce(function (newData, item) {
        // Treat Arrays
        if (item.name.substring(item.name.length - 2) === '[]') {
            var key = item.name.substring(0, item.name.length);
            if(typeof(newData[key]) === 'undefined') {
                newData[key] = [];
            }
            newData[key].push(item.value);
        } else {
            newData[item.name] = item.value;
        }
        return newData;
    }, {});
    
    console.log(data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form id="my_form">
      <select name="muli_select[]" multiple="multiple">
        <option value="1" selected>Value 1</option>
        <option value="2" selected>Value 2</option>
        <option value="3">Value 3 Not selected</option>
      </select>
      <br>
      <input name="my_text" type="hidden" value="Hidden Text"/>
      <input name="my_text2" type="text" value="Shown Text"/>
      <br>
      
      <input type="radio" name="gender" value="male" checked> Male<br>
      <input type="radio" name="gender" value="female"> Female
    </form>

    0 讨论(0)
  • 2020-11-28 06:55

    Give your form an id(form-id)

    var jsoNform = $("#form-id").serializeObject();
    
    jQuery.fn.serializeObject = function () {
        var formData = {};
        var formArray = this.serializeArray();
        for (var i = 0, n = formArray.length; i < n; ++i)
             formData[formArray[i].name] = formArray[i].value;
         return formData;
    };
    
    0 讨论(0)
提交回复
热议问题