Search code examples
javascripthtmlradio-button

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 (i.e. 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.


Solution

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