Monday 4 February 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...