I have a form with many input fields.
When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?
The jQuery val() function and serialize() function are built-in functions in jQuery. The val() function can be used to get the first element's value attribute in the set of matched elements. The serializeArray() function is used to get from data; it returns the array of objects by serializing the form data.
The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data. Parameter: It does not accept any parameter.
To iterate through all the inputs in a form you can do this: $("form#formID :input"). each(function(){ var input = $(this); // This is the jquery object of the input, do what you will });
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.
$('#myForm').submit(function() { // get all the inputs into an array. var $inputs = $('#myForm :input'); // not sure if you wanted this, but I thought I'd add it. // get an associative array of just the values. var values = {}; $inputs.each(function() { values[this.name] = $(this).val(); }); });
Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray
:
var values = {}; $.each($('#myForm').serializeArray(), function(i, field) { values[field.name] = field.value; });
Note that this snippet will fail on <select multiple>
elements.
It appears that the new HTML 5 form inputs don't work with serializeArray
in jQuery version 1.3. This works in version 1.4+
Late to the party on this question, but this is even easier:
$('#myForm').submit(function() { // Get all the forms elements and their values in one step var values = $(this).serialize(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With