21

I recently came across a StackOverflow answer that gave excellent instructions on how to get the value of a checked radio button using jQuery:

var radioVal = $("#myFormID input:radio[name='radioFieldName']:checked").val();
alert('Selected radio button value = ' + radioVal);

Now I'm trying to find the zero-based index of the checked radio button. I thought it would be relatively simple:

var radioIdx = $("#myFormID input:radio[name='radioFieldName']:checked").index();

However, radioIdx is always returning a value of -1. Any ideas on what I might be doing wrong?

Community
  • 1
  • 1
Mass Dot Net
  • 2,150
  • 9
  • 38
  • 50
  • The selector you have will match just one radio button. You are expecting jQuery to tell you its index *in what collection exactly*? – Jon Mar 22 '11 at 17:44
  • I'm not sure if I understand what you mean. I'm simply trying to identify the zero-based index of the radio button in the collection `radioFieldName` in `
    `.
    – Mass Dot Net Mar 22 '11 at 18:07

6 Answers6

37

This should work. You could do it all in one line but I broke it up to make it easier to read:

var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.find(':checked'));

EDIT: Verify that your selector is correct. Break it down step by step:

var radioButtons = $("#myFormID input:radio[name='radioFieldName']");

// this should contain the count of all your radio buttons
var totalFound = radioButtons.length;

// this should contain the checked one
var checkedRadioButton = radioButtons.find(':checked');

// this should get the index of the found radio button based on the list of all
var selectedIndex = radioButtons.index(checkedRadioButton);

Which step is not producing the expected value in these?

EDIT: To show final solution

var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.filter(':checked'));
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • 1
    @AspNyc maybe your selector is incorrect. In my example how many items are you getting for `radioButtons`? That should contain all your radio button controls. If that is empty then your selector is incorrect to find the radio buttons. – Kelsey Mar 22 '11 at 18:05
  • The first selector finds 7 matches, which is correct: there are 7 `radioFieldName` radio buttons in `
    `. However, when I look at `radioButtons.find(':checked').length`, it returns a value of `0`.
    – Mass Dot Net Mar 22 '11 at 18:15
  • Something noteworthy: when I changed `find()` to `filter()`, `radioButtons.filter(':checked').length` returns a value of `1`, which is good. In addition, when I call `radioButtons.filter(':checked').val()` it still returns the value of the checked radio button. But when I change it to `radioButtons.filter(':checked').index()`, it still returns `-1`. – Mass Dot Net Mar 22 '11 at 18:23
  • @AspNyc something seems odd... that should find the item in the list that is checked. Can you use setup an alert for each item in the list and display the checked property? – Kelsey Mar 22 '11 at 18:25
  • 2
    @AspNyc try `radioButtons.index(radioButtons.filter(':checked'));` – Kelsey Mar 22 '11 at 18:27
  • **BINGO!** That did the trick... now can you explain what's going on with this latest statement that the other suggestions here weren't doing? – Mass Dot Net Mar 22 '11 at 18:43
  • @AspNyc `index(radioButtonLookingFor)` is taking in the radio button selected (which is found by the filter) and finding it in the list of all radio buttons. It's looking for that object in your list. – Kelsey Mar 22 '11 at 18:45
  • @Kelsey: That makes sense... I'm just surprised that I couldn't use index() in the same way I used val(), and that it required rewriting my statement in a very different way than if I wanted to get the checked value. – Mass Dot Net Mar 22 '11 at 18:49
  • Also, your solution was extensible enough that it answered the other question I had (but didn't post about): how to get the index of a specific radio button value: `alert('Index of value=' + valueToFind + ' is ' + radioButtons.index(radioButtons.filter('input[value=' + valueToFind + ']')));` – Mass Dot Net Mar 22 '11 at 18:59
  • 1
    index() was being used improperly for your use case. You have to use index on the selector that selects all inputs, not just the checked one(s). – JD Smith May 27 '14 at 21:21
  • @Kelsey I don't think you want to use `.find()` at all, which looks for descendents. Suggest (a) change to `.filter()` instead in the first two code blocks, and (b) remove the "final solution" as it then becomes identical to the first block of code. – Bob Stein Jan 27 '17 at 16:05
7

Try using the form of index that allows you to specify an element in a collection and returns it's relative position in the collection:

var radioIdx = $(":radio[name='radioFieldName']")
                    .index($(":radio[name='radioFieldName']:checked")); 

or the version that finds the first item matching a selector that is in another collection and reports it's position in the second collection.

var radioIdx = $(":radio[name='radioFieldName']:checked")
                   .index(":radio[name='radioFieldName']");
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • I was about to post the same thing... for a given collection of elements, find the index of this specific element. – Mayo Mar 22 '11 at 17:46
  • Unfortunately, I'm still getting a -1 value. – Mass Dot Net Mar 22 '11 at 18:00
  • @AspNyc - try using the alternative that searches for an element rather than a selector. See my update (and simplification of your selectors -- you probably don't need the `#myForm input` unless you have multiple forms containing the same named elements). The previous form I had the selectors backward. I'll also update with a version that uses that form as well. – tvanfosson Mar 22 '11 at 18:48
  • Still no luck with your statement. However, Kelsey was able to figure it out: `radioButtons.index(radioButtons.filter(':checked'));` did the trick. – Mass Dot Net Mar 22 '11 at 18:53
2

There are a couple of options:

1) Enumerate through the radio button list (aka without the :checked modifier) and test to see if it is checked; if so, you have the id of the element in the group.

2) The better way (imo), is to simply associate some data with each element and pull that data. So if you give the element a 'data-index' attribute with the value, you can then simply call

$('#myFormID input:radio[name='radioFieldName']:checked').data('index')

And have the value.

Tejs
  • 40,736
  • 10
  • 68
  • 86
0

use this

    alert($("input[name=checkname]:checked").map(function () {return this.value;}).get().join(","));
atabak
  • 193
  • 1
  • 4
0

Though this is old, but try this (assuming you're within the click function of the radio buttons)

$('#myFormID input:radio[name=radioFieldName]').click(function(){
  var index = $('#myFormID input:radio[name=radioFieldName]').index(this);
  alert(index);
});
Obi
  • 49
  • 4
0

it return -1 because you get the value before any radiobutton was checked. i think you miss placed your listener and index checked. I just got the same error, but finally found the answer, i get the index before anything was checked, please check your code arrangement, the code stated above is right.

Bhimbim
  • 1,348
  • 2
  • 19
  • 15