jQuery选择表单数组名称

I have a form that looks like the following:

<input type="text" name="item[101][0][date]" value="2012" />
<input type="text" name="item[101][0][price]" value="10.00" />
<input type="text" name="item[101][0][colour]" value="orange" />
<input type="text" name="item[101][1][date]" value="2013" />
<input type="text" name="item[101][1][price]" value="5.00" />
<input type="text" name="item[101][1][colour]" value="blue" />

And I would like to be able to select the entire array from the first 2 keys and store the whole lot as an array in javascript so I can send it via AJAX to PHP.

I've got this in jQuery at the moment, but it doesn't seem to produce what I'm after.

var products = $('input[name~="item['+itemCode+']['+basketId+']"]');

Where itemCode and basketId and retrieved from a submit button (which is working).

Once I have this array called "products" I know how to serialise it and send it as a post request, I just don't seem to be able to end up with an array such as:

products[101][0][date] = 2012
products[101][0][price] = 10.00
products[101][0][colour] = orange

Or:

products[101][1][date] = 2013
products[101][1][price] = 5.00
products[101][1][colour] = blue

Any help with this would be appreciated!

Thanks!

You are using the attribute contains word selector (name~=value), which does a slightly different thing from what you want:

This selector matches the test string against each word in the attribute value, where a "word" is defined as a string delimited by whitespace. The selector matches if the test string is exactly equal to any of the words.

Use the attribute starts with selector (name^=value):

var products = $('input[name^="item['+itemCode+']['+basketId+']"]');

Either use the attribute contains selector (name*=value):

var products = $('input[name*="item['+itemCode+']['+basketId+']"]');

DEMO.

I would suggest using data-* HTML5 attributes to store data at different holders instead of everything stored in the name. Something like:

<input type="text" data-category="101" data-index="0" data-id="date" value="2012" />

Selection then would be performed the following way:

var input = $('input[data-category=' + category + '][data-index=' + index + '][data-id=' + id + ']');

This also allows you to select all items of the same category easily, or with the same index, etc.

The array would be constructed like:

var products = [];
// Define category, index and id
products[category][index][id] = $('input[data-category=' + category + '][data-index=' + index + '][data-id=' + id + ']').val();