开发者

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).开发者_JAVA技巧

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜