Reputation: 405
I have some input elements with same name and suffix, but those input have a index (an array) like parameterName[index].PropertyName
something like this:
<input type="text" name="stocks[0].Key" value="MSFT" />
<input type="text" name="stocks[1].Key" value="AAPL" />
<input type="text" name="stocks[n].Key" value="ZZZZ" />
How I can iterate over those input elements?
something like
$("#stocks[x].Key").each
Upvotes: 1
Views: 906
Reputation: 122
Wrap the input elements in a ul and li, like this:
<ul id="foo">
<li id="1">
<input type="text" name="stocks[0].Key" value="MSFT" />
</li>
<li id="2">
<input type="text" name="stocks[1].Key" value="AAPL" />
</li>
</ul>
Then you can access the input elements as follows:
$('#foo li').each( function() {
id = this.id;
mytext = $(this).find('input[type=text]').val();
});
Upvotes: 1
Reputation: 87203
You can use starts with
: ^ and ends with
: $ in the selector:
$('[name^="stocks["][name$="Key"]').each(function() {
console.log($(this).val());
});
This will select elements if the name attribute value starts
with stocks[
and ends
with Key
.
Demo: http://jsfiddle.net/tusharj/0wbzud85/2/
Docs: https://api.jquery.com/attribute-equals-selector/
Upvotes: 3