Bug Tracker

Opened 9 years ago

Closed 9 years ago

#8331 closed bug (invalid)

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

Reported by: clint@… 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

Change History (2)

comment:1 Changed 9 years ago by clint@…

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

comment:2 Changed 9 years ago by jitter

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();
Note: See TracTickets for help on using tickets.