I\'m having a bit of trouble serializing a form
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"}
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.
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>
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;
};