How to get form data as an object in jquery

I tried jQuery('#form_id').serialize() . This only returns form data as a url encoded string. Is it possible to get form data as an object?

+48
javascript jquery
Mar 08 '10 at 17:17
source share
2 answers

Have you tried "serializeArray"? This gives you an array of names and values. You can turn this into an object if you want:

 var paramObj = {}; $.each($('#myForm').serializeArray(), function(_, kv) { paramObj[kv.name] = kv.value; }); 

(I need to check again what jQuery does with arrays, I think it encodes them as Javascript array values, but I'm not 100% sure.)

there is no change ah, it does not set multivalued parameters in the form of arrays - you get repetitions with the same name. So the make-object code should look like this:

 var paramObj = {}; $.each($('#myForm').serializeArray(), function(_, kv) { if (paramObj.hasOwnProperty(kv.name)) { paramObj[kv.name] = $.makeArray(paramObj[kv.name]); paramObj[kv.name].push(kv.value); } else { paramObj[kv.name] = kv.value; } }); 

(or something like that, maybe a little squeeze).

+75
Mar 08 '10 at 17:21
source share

You can take a look at the serializeArray function:

 $('#form_id').serializeArray() 
+26
Mar 08 '10 at 17:21
source share



All Articles