3

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

0

1 Answer 1

2

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();
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.