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?
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?
Associative? Not without some work, but you can use generic selectors:
var items = new Array();
$('#form_id:input').each(function (el) {
items[el.name] = el;
});
$('#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.
$('#myForm').bind('submit', function () {
var elements = this.elements;
});
The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.
Late to the party on this question, but this even easier:
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $('#myForm').serialize();
});
The jquery.form plugin may help with what others are looking for that end up on this question. I'm not sure if it directly does what you want or not.
There is also the serializeArray function.
The top answer doesn't seem to take care of checkbox submission and will submit values even checkbox is not checked.
When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked. I added a new selector to just get the submit-able form elements:
$.extend($.expr[':'],{
submitable: function(a){
if($(a).is(':checkbox:not(:checked)'))
{
return false;
}
else if($(a).is(':input'))
{
return true;
}
else
{
return false;
}
}
});
usage:
$('#form_id :submitable');
I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would.
I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type.