最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get id value by index using name jquery - Stack Overflow

programmeradmin2浏览0评论

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
  • You had a typo vat instead of var. And you better add the tagName to the selector. – gdoron Commented Jun 9, 2012 at 20:48
Add a comment  | 

3 Answers 3

Reset to default 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

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.
发布评论

评论列表(0)

  1. 暂无评论