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
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:
.element
.element
checked=true
..element
.checked=true
.//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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With