使用jQuery切换单选按钮

我正在尝试使用jQuery切换几个单选按钮。 但事实certificate并非如此简单。


fast
slow
$('#toggler').click(function() { $('input[name="speeds"]').each(function(){ $(this).prop("checked", !$(this).prop("checked")); }); });

http://jsfiddle.net/beC7q/

任何人都可以解释为什么上面的代码不起作用?

如果只有两个单选按钮

 $('#toggler').click(function() { $('input[type="radio"]').not(':checked').prop("checked", true); }); 

演示: 小提琴

如果有超过2个元素

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

演示: 小提琴

组中的单选按钮(即,具有相同name值的input s)已经是互斥的。 您只需修改一个“已检查”状态即可更改整个组的状态:

例如,此代码始终将组中的最后一个无线电设置为“已选中”:

 $('#toggler').click(function() { $('input[type="radio"][name="speeds"]').last().prop('checked', true); }); 

DEMO