FabianSilva
FabianSilva

Reputation: 405

iterate over array if input element with same name, different index, same suffix

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

Answers (2)

ryog
ryog

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

Tushar
Tushar

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

Related Questions