I need to serialize an associative JavaScript array.
It’s a simple form of products and a numeric values, but just after building the array seems empty.
The code is here: http://jsbin.com/usupi6/4/edit
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, don’t use JS arrays for “associative arrays”. Use plain objects:
That is why
$.eachdoes not work: jQuery recognizes that you pass an array and is only iterating over numerical properties. All others will be ignored.An array is supposed to have only entries with numerical keys. You can assign string keys, but a lot of functions will not take them into account.
Better:
As you use jQuery, you can use
jQuery.param[docs] for serialization. You just have to construct the proper input array:No need to implement your own URI encoding function.
DEMO
Best:
If you give the input fields a proper
name:you can even make use of
.serialize()[docs] and greatly reduce the amount of code (I use the next adjacent selector [docs]):(it will include
0values though).DEMO