2013-10-02 2 views
4

jQuery를 사용하여 두 개의 라디오 버튼을 토글하려고합니다. 그러나 그렇게 단순하지는 않습니다. 위의 코드는 작동하지 않는 이유 jQuery로 라디오 버튼 토글

<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/

는 사람이 설명해 주시겠습니까?

답변

24

두 라디오 버튼

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

데모 : Fiddle

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

데모 : A의 Fiddle

8

라디오 버튼 그룹 (예 : input s 동일한 name 값)은 이미 상호 배타적입니다. 당신은 전체 그룹의 상태를 변경하는 하나의 "확인"상태를 수정해야합니다

이 코드, 예를 들어, 항상 그룹의 마지막 라디오를 설정합니다에 "확인"

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

DEMO