Bug Tracker

Modify

Ticket #8331 (closed bug: invalid)

Opened 2 years ago

Last modified 2 years ago

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

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

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

comment:1 Changed 2 years ago by clint@…

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

comment:2 Changed 2 years ago by jitter

  • Priority changed from undecided to low
  • Resolution set to invalid
  • Status changed from new to closed
  • Component changed from unfiled to misc

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();

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.