4

html

<input id="1" name="myText" type="text" value="20"/>
<input id="2" name="myText" type="text" value="30"/>
<input id="3" name="myText" type="text" value="40"/>

How can I get id value by index using name?

The following code snippet is not working

var getVal = $('[name="myText"]').index(1);
gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
Shahid Ghafoor
  • 3,329
  • 16
  • 62
  • 117

3 Answers3

10

jQuery holds the DOM elements in the set like an array so you can use the indexes operator([]) to get the element, or get the jQuery object that wraps the desired element with :eq(n) `.eq(n)`

$('input[name="myText"]:eq(1)').attr('id')

You should mention what to you consider to be index(1) the first or the second:

$('input[name="myText"]:eq(0)').attr('id') // First
$('input[name="myText"]:eq(1)').attr('id') // Second

Or:

$('input[name="myText"]')[0].id // First
gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
  • index(1) means obviously second – Shahid Ghafoor Jun 09 '12 at 20:40
  • @ShahidGhafoor. It's not that obvious, css selectors use the 1-base index... _"Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.myclass:eq(1)') selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification."_ – gdoron is supporting Monica Jun 09 '12 at 20:41
  • dear, but this is javascript(jquery) code. means 0-based indexing ;-)..kidding @gdoron – Shahid Ghafoor Jun 09 '12 at 21:06
4

If you want the first value, you can filter and use the attr method to get the value of the id attribute.

var getVal = $('[name="myText"]:first').attr('id'); // first id

If you want some other element, you can use eq and choose the zero-based element in the collection.

var getVal = $('[name="myText"]:eq(1)').attr('id'); // second id
tvanfosson
  • 509,016
  • 97
  • 693
  • 791
2

My answer refers to accessing elements in the jQuery result object by index. You can use selectors such as :eq indicated in other answers.

However, you can use .get(1) instead of your index.

var id = $('[name="myText"]').get(1).id;

Is equivalent to

var id = $('[name="myText"]:eq(1)').attr('id');

Example: http://jsfiddle.net/HackedByChinese/UmKw6/1/

The second method is the preferred route, since it means you never leave the jQuery result object and thus can chain other jQuery calls in one statement.

var id = $('[name="myText"]:eq(1)').css('color', 'red').attr('id'); // example of chaining jQuery methods. sets the text color to red and then returns the id.
moribvndvs
  • 41,675
  • 10
  • 134
  • 146