Tuesday 24 May 2016

Convert form data to JavaScript object with jQuery



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();


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...