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);
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);
Share
Improve this question
edited Jun 9, 2012 at 20:43
gdoron
150k59 gold badges302 silver badges371 bronze badges
asked Jun 9, 2012 at 20:30
Shahid GhafoorShahid Ghafoor
3,10318 gold badges73 silver badges125 bronze badges
1
|
3 Answers
Reset to default 10jQuery 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
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
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.
vat
instead ofvar
. And you better add the tagName to the selector. – gdoron Commented Jun 9, 2012 at 20:48