How do I convert all elements of my form to a JavaScript object?
I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by $('#formid').serialize();
, nor do I want the map returned by $('#formid').serializeArray();
serializeArray already does exactly that. You just need to massage the data into your required format:
function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
Watch out for hidden fields which have the same name as real inputs as they will get overwritten.