Reputation: 3103
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);
Upvotes: 3
Views: 36129
Reputation: 150313
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
Upvotes: 10
Reputation: 42495
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.
Upvotes: 2
Reputation: 532755
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
Upvotes: 4