Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - Toggling Radio Buttons with jQuery

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...