jQuery serializeArray: Why Not An Associative Array?
I’m trying to examine and modify form variables from jQuery by catching the submit event. jQuery has a serializeArray method that hands you the form variables in a nice array. For example:
$('#someform').submit( function() {
$.post("/some/url/", $(this).serializeArray(),
function(data){
console.log(data);
}, "json");
return false;
} );
This is great, but the result of serializeArray is an integer indexed array whose values are (key,value) pairs. Eg.
var data = $(this).serializeArray(),
console.log( data[0] );
>> output: Object name=somename value=537
I’m wondering why the array looks like this, instead of being a dictionary (associate array, hash, or whatever you want to call it) such that the keys are “name”s and values are “value”s. Eg.
var data = $(this).serializeArray(),
console.log( data.somename );
>> output: 537
Anybody know the answer?
Manage your expenses via Email, SMS, Twitter, Voice (Jott: Call and say your expense), IM (Yahoo, AIM, MSN), or Web.
I’m guessing it’s for two reasons: firstly, to preserve order and secondly, because it’s possible to have several fields in a form with the same name (which results in something like ?perm=can-write&perm=can-read being sent to the server).
Simon’s second reason is the key one AFAIK.
An associative array value can itself be an array itself, so it could accommodate the multi-value scenario. And I don’t think order means much, does it? It would seem bad practice to depend on the order of elements as rendered in the form.
My use case is to examine and on occasion modify the form values before submitting them, and the indexed array is returned by serializeArray is clumsy for that. If $.post can deal with associative arrays I guess I’ll write a simple conversion routine.