Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  18] [ 5]  / answers: 1 / hits: 53583  / 11 Years ago, wed, october 2, 2013, 12:00:00

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));
});
});


http://jsfiddle.net/beC7q/



Could anyone please explain why the code above does not work?


More From » jquery

 Answers
3

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


[#75276] Tuesday, October 1, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;