I am new to jquery and i think this is just a basic problem. `
<input type="text" name="text1" value=""></input>
<input type="text" name="text2" value=""></input>
<input type="text" name="text3" value=""></input>
<input type="text" name="text4" value=""></input>
<input type="text" name="text5" value=""></input>
<input type="submit" value="submit"></input>
<pre id="result">
</pre>
</form>`
This is my html form and i am using following jquery function to produce json object
$.fn.serializeObject = function()
{
var o = {};
var d={};
var a = this.serializeArray();
$.each(a, function(i,n) {
o['name'] = n['name'];
o['content'] =(n['value']);
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
on runnig the above html i am getting the output {"name":"text5","content":"sdsd"}
just the final text field. i know am wrong somewhere . can someone help me to fix it. thanks in advance
That's because you are overwriting object's properties and the last values win, you can use an array and it's push method.
$.fn.serializeObject = function () {
var o = [];
var a = this.serializeArray();
$.each(a, function (i, n) {
o.push({
name: n['name'],
content: n['value']
})
});
return o;
};
http://jsfiddle.net/kxM3e/
Using jQuery map method:
$.fn.serializeObject = function () {
return this.find('input, textarea, select').map(function(){
return { name: this.name, content: this.value };
}).get();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With