jsfiddle

http://jsfiddle.net/cCBUh/2/

Information

  • I have 3 choices. Only click on the labels, not on the radio buttons.
  • When clicking on the different labels, different radio buttons are checked.
  • In the console it says "clicked" when ever a label is clicked just to make sure that happens.
  • When clicking on the same label twice, the console says "checked", telling us it's already checked.
  • If the label is already checked it should remove the checked from all the radio buttons, resetting it, like it's from the start.

Problem

When clicking on the radio button the second time the click don't remove the checked from all the radio buttons. Why is that? Solution?

HTML

<div class="panel">
    <label for="radio-1">Radio 1</label>
    <label for="radio-2">Radio 2</label>
    <label for="radio-3">Radio 3</label>
    <input type="radio" id="radio-1" name="group-1">
    <input type="radio" id="radio-2" name="group-1">
    <input type="radio" id="radio-3" name="group-1">
</div>

jQuery

jQuery(document).ready(function($) {
    $('.panel label').on( "click", function(e) {
        console.log('clicked');
        var my_id = $(this).attr('for');
        if( $('.panel #' + my_id).is(':checked') ) {
            console.log('checked');
            $('.panel input[type="radio"]').prop('checked', false);
        }
    });
});
有帮助吗?

解决方案

I think the problem is, that the default click-behaviour on a label with an id-attribute forces this. I changed your javascript to do what you want and added a bit more debug:

http://jsfiddle.net/cCBUh/15/

jQuery(document).ready(function($) {
    $('.panel label').on( "click", function(e) {
        // prevent the html to automatically check the corresponding checkbox
        e.preventDefault();
        var my_id = $(this).attr('for');
        console.log('clicked: ' + my_id);
        if( $('#' + my_id).is(':checked') ) {
            console.log('checked: ' + my_id);
            $('#' + my_id).prop('checked', false);
        } else {
            console.log('check now: ' + my_id);
            $('#' + my_id).prop('checked', true);
        }
    });
});

But you might also want to apply that behaviour to onClick on the radio buttons itself?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top