Monday, February 4, 2019

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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...