Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through array using jquery returns only last object

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

like image 799
ani Avatar asked Mar 19 '26 11:03

ani


1 Answers

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();
};
like image 116
undefined Avatar answered Mar 22 '26 01:03

undefined