如何通过再次单击它来取消选中单选按钮

时间:2010-11-30 10:43:20

标签: javascript html radio-button

我一直在搜索很多主题,但我没有发现任何与我的问题完全对应的内容:

我想要取消选中单选按钮(例如,在已经选中的情况下点击单选按钮取消选中)。

我发现一些使用隐藏单选按钮作为临时比较对象的解决方案,但这不适合我现有的上下文,所以我想在没有其他单选按钮的情况下也这样做。

我试图在“onclick”事件上测试并更改单选按钮的状态/值,但它还不是很成功......

提前致谢, 克莱姆。

3 个答案:

答案 0 :(得分:16)

那不是单选按钮。如果您尝试使其工作,您只会混淆用户。

如果您想要可以检查然后取消选中的内容,请使用复选框。单选按钮用于选择一组选项中的一个。

答案 1 :(得分:4)

更好:

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');
}"

答案 2 :(得分:2)

我知道这种行为对于单选按钮是非标准的,但海报要求功能。以下是我过去使用过的代码。我发现它不是最优化的(假设有大量的单选按钮),但我还没有花时间进行优化。

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