Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the first radio button of multiple radio buttons groups with jQuery

I would like to automatically select the first radio button of multiple radio buttons groups.

<div class="element">
<input type="radio" name="group1" value="1">
<input type="radio" name="group1" value="2">
<input type="radio" name="group1" value="3">
</div>

<div class="element">
<input type="radio" name="group2" value="1">
<input type="radio" name="group2" value="2">
<input type="radio" name="group2" value="3">
</div>

Here is the thing, while this works:

$('.element').each(function(){
    $(this).find('input[type=radio]:first').attr('checked', true);
});

I can't figure out why I can't make it work using the :first selector using the each() method

The code below doesn't work: it only selects the first radio button in the first div, can you tell me why?

$('.element input[type=radio]:first').each(function(){
    $(this).attr('checked', true);
});

Thanks

like image 585
Vincent Avatar asked Dec 03 '22 06:12

Vincent


1 Answers

The first selector loops through each .element. The second selector loops through each element input[type=radio]:first, which consists of only one element.

I've translated your code to a human-readable sequence:

  1. Select .element
    Go through each .element
    Find the first occurence of a radio input element
    Set checked=true.
  2. Select the first radio input element which is a child of .element.
    Loop through each element which matches the selector (just one)
    Set checked=true.


Alternative ways:
//Alternative method
$('element').each(function(){
    $('input[type=radio]', this).get(0).checked = true;
});

//Another method
$('element').each(function(){
    $('input[type=radio]:first', this).attr('checked', true);
});
like image 190
Rob W Avatar answered Apr 27 '23 08:04

Rob W