Skip to main content

Bug Tracker

Side navigation

#8331 closed bug (invalid)

Opened February 20, 2011 09:04PM UTC

Closed February 21, 2011 12:11AM UTC

index(':checked') doesn't work as expected

Reported by: clint@traveljur.com Owned by:
Priority: low Milestone: 1.next
Component: misc Version: 1.5
Keywords: Cc:
Blocked by: Blocking:
Description

Maybe I haven't understood the index() function correctly, but I thought that this should work:


   var radios = $('#id input');
   var checked = radios.index(':checked');

However, it always gives me -1

If I do:


    var checked = radios.index(radios.filter(':checked'));

it works as expected, but surely the first version is intended?

thanks

clint

Attachments (0)
Change History (2)

Changed February 20, 2011 09:08PM UTC by clint@traveljury.com comment:1

Example provided here: http://jsfiddle.net/QECxW/

Changed February 21, 2011 12:11AM UTC by jitter comment:2

component: unfiledmisc
priority: undecidedlow
resolution: → invalid
status: newclosed

Thanks for taking the time to contribute to the jQuery project by writing a bug report.

This isn't a bug, you just misread what .index() does when you pass it a selector. The documentation for .index( selector ) reads:

>selector A selector representing a jQuery collection in which to look for an element.

and

>If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.

This says jQuery tells you the position of the first element in the jQuery collection relative to the elements you selector matches.

In your test case this means jQuery checks if <input type="radio" name="one" value="bar" /> is in the collection matched by :checked which of course returns -1, as this input isn't checked and thus not in the collection described by your selector.

So what you probably actually want to do is

//what is the index of the checked radio button
$("#id input:checked").index();