Is there a way I can access the array of data that the browser compiles on a form submit – before the actual GET/POST operation in js/jq?
$("form").submit(function(event){
event.preventDefault();
//give me the data array here
});
I’m finding myself increasingly using AJAX – I call event.preventDefault(), grab the name/value pairs of all the elements contained in $(this) (the form) and then push them to the server via $.post(). It’s becoming a pain the neck to assemble the data array manually. It would be great if a plugin existed of sorts:
$data = $("form").gimmeData();
Does something like this exist that supports all the major HTML input elements? Am I approaching this way wrong? Thanks!
Yes, jQuery has a “serializeArray()” method that does pretty much what you ask for.
It returns an array like:
You can turn that into an object like this:
If a name appears more than once in a form, then its “value” will be an array of values from the separate fields.