Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to get the index of a checked radio button

Tags:

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?

like image 289
Mass Dot Net Avatar asked Mar 22 '11 17:03

Mass Dot Net


People also ask

How to get index of selected radio button in javascript?

Using the . each() function you can grab the index of each element. Using the .is(':checked') function you can check if something is checked.

How to show checked radio button in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.

How to check radio button in jQuery by value?

Answer: Use the jQuery :checked selector You can simply use the jQuery :checked selector in combination with the val() method to find the value of the selected radio button inside a group.

When radio button is selected jQuery?

To select a radio button (Male). The radio button is 0-based, so the 'Male' = '0', 'Female' = '1' and 'Unknown' = '2'. $('input:radio[name=sex]:nth(0)'). attr('checked',true); or $('input:radio[name=sex]')[0].


1 Answers

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')); 
like image 146
Kelsey Avatar answered Oct 12 '22 01:10

Kelsey