Ho un modulo con molti campi di input.
Quando catturo l'evento submit form con jQuery, è possibile ottenere tutti i campi di input di quel modulo in un array associativo?
$('#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();
});
});
Grazie al suggerimento di Simon_Weaver, ecco un altro modo per farlo, usando serializeArray
:
var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
Notate che questo snippet fallirà su elementi <select multiple>
.
Sembra che i nuovi input del modulo HTML 5 non funzionino con serializeArray
in jQuery versione 1.3. Questo funziona nella versione 1.4+