0

when i'm iterating a collection of inputs, how can I get the current radio index if the input is part of a group of radios?

$('input').each(function(){

  if($(this).is(':radio')){
    // here get the index of the radio in the radio group,
    // like 1, 2, 3 etc... 
  }


});

The index should be relative to the radio group, no the entire collection of input elements.

The group is determined by the input name (inputs having the same name).

thelolcat
  • 10,995
  • 21
  • 60
  • 102

3 Answers3

4

To find the position of the radio within the group defined by the radio's name attribute:

$('input:radio').each(
    function(){
        console.log($(this).index('[name="' + this.name + '"]'));
    });​

JS Fiddle proof of concept.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2
$('input:radio').each(function(el, i){
    //i is your index
});

Update: I found this as well for finding the selected value of a radio group. How can I know which radio button is selected via jQuery?

Community
  • 1
  • 1
Joe
  • 6,401
  • 3
  • 28
  • 32
1
var inputs = $('input');

inputs.each(function()
{
  if ($(this).is(':radio')) {
    console.log(inputs.index(this));
  }
});    
Lior Cohen
  • 8,985
  • 2
  • 29
  • 27