1

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

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I not mentioned this... but I also have another inputs like <input type="text" name="stocks[0].Other" value="YYYYY" /> that not like to select, sorry for not mention it --> update: I will try it :) thanks you so much
1

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();   
}); 

1 Comment

I can't change each input element, but you give a good idea, seems that also it is posible to wrap all input elements in a div and see all childs of this "root" div element...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.