Reputation: 12123
I am trying to toggle a couple of radio buttons using jQuery. But it is turning out to be not so simple.
<button id="toggler">click me</button><br>
<input type="radio" name="speeds" value="fast" checked>fast<br>
<input type="radio" name="speeds" value="slow">slow<br>
$('#toggler').click(function() {
$('input[name="speeds"]').each(function(){
$(this).prop("checked", !$(this).prop("checked"));
});
});
Could anyone please explain why the code above does not work?
Upvotes: 11
Views: 55934
Reputation: 21708
Radio buttons in a group (i.e., input
s with the same name
value) are already mutually exclusive. You only need to modify the "checked" state of one to change the entire group's state:
This code, for example, would always set the last radio in the group to "checked":
$('#toggler').click(function() {
$('input[type="radio"][name="speeds"]').last().prop('checked', true);
});
Upvotes: 9
Reputation: 388316
If there are only two radio buttons
$('#toggler').click(function() {
$('input[type="radio"]').not(':checked').prop("checked", true);
});
Demo: Fiddle
If there are more than 2 elements
var $radios = $('input[type="radio"][name="speeds"]')
$('#toggler').click(function() {
var $checked = $radios.filter(':checked');
var $next = $radios.eq($radios.index($checked) + 1);
if(!$next.length){
$next = $radios.first();
}
$next.prop("checked", true);
});
Demo: Fiddle
Upvotes: 37