简体   繁体   中英

How to uncheck a radio button by clicking on it a second time

I have been searching in a lot of topics but I haven't found anything that really correspond to my problem :

I want to make radio buttons uncheckable (ie uncheck a radio button by clicking on it when it's already checked).

I found some solutions using a hidden radio button as a temporary comparison object but this doesn't fits to my existing context, so I would like to do the same without another radio button.

I tried to simply test and change the status/value of the radio button on "onclick" event but it hasn't been very successfull...

Thanks in advance, Clem.

That's not what radio buttons are. If you try to make this work, you will just confuse your users.

If you want something that can be checked and then unchecked, use a checkbox. Radio buttons are for selecting exactly one of some set of options.

better so:

onclick="
var isChecked = $(this).attr('is_che');
if (isChecked) {
     $(this).removeAttr('checked');
     $(this).removeAttr('is_che');
}
else {
     $(this).attr('checked', 'checked');
     $(this).attr('is_che', 'true');
}"

I know this sort of action is non-standard for radio buttons, but the poster requested the functionality. The following is code that I've used in the past. I've found it not to be the most optimized (assuming a large # of radio buttons), but I also haven't taken the time to do that optimization.

    //  Allow for radio button unchecking
$(function(){
    var allRadios = $('input[type=radio]')
    var radioChecked;

    var setCurrent = function(e) {
        var obj = e.target;
        radioChecked = $(obj).attr('checked');
    }

    var setCheck = function(e) {
        if (e.type == 'keypress' && e.charCode != 32) {
            return false;
        }
        var obj = e.target;
        if (radioChecked) {
            $(obj).attr('checked', false);
        } else {
            $(obj).attr('checked', true);
        }
    }

    $.each(allRadios, function(i, val) {
        var label = $('label[for=' + $(this).attr("id") + ']');
        $(this).bind('mousedown keydown', function(e){
            setCurrent(e);
        });

        label.bind('mousedown keydown', function(e){
            e.target = $('#' + $(this).attr("for"));
            setCurrent(e);
        });

        $(this).bind('click', function(e){
            setCheck(e);    
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM