Javascript / JQuery取消选择单选按钮 [英] Javascript/ JQuery Deselecting radio buttons

查看:95
本文介绍了Javascript / JQuery取消选择单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下javascript,我想用它来让用户通过点击取消选择所选的单选按钮。 (我知道这不是标准的,但系统要求它:)

I have the following javascript, which I want to use to enable the user to deselect a selected radio button by clicking it. (I know this is not standard, but it is required by the system :)

DeselectRadioButton = {
    setup: function () {
        $(".deselectRadioButton").click(function () {
            if ($(this).is(':checked')) {
                alert("I am checked!");
                ($(this).removeAttr('checked'));
            }
        });
    }
};

我的问题是当我选择一个未选中的单选按钮时,它会在警报显示后立即取消选择它。

My issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.

我想我在项目更改后收到了这个事件 - 如何修复此代码以使我的单选按钮无法选择?

I guess I am receiving the event after the item has changed - how can I fix this code to make my radio button deselectable?

谢谢!

推荐答案


然而,主要问题是当我
选择一个未选中的单选按钮,
警告显示后立即取消选择它。

However, the main issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.

它似乎无法阻止单选按钮的默认行为,其中返回false e.preventDefault() as触发单击处理程序时始终检查单选按钮。解决这个问题的一种方法是在单选按钮上添加一个单独的类,并将其用作指示符。

It seems you can't prevent the default behavior of a radio button with either return false or e.preventDefault() as the radio button always is checked when the click handler is fired. One way around this was to add a separate class to the radio button and use that as your indicator.

$(".deselectRadioButton").click( function(e){
    if($(this).hasClass("on")){
       $(this).removeAttr('checked');
    }
    $(this).toggleClass("on");
}).filter(":checked").addClass("on");

jsfiddle

这篇关于Javascript / JQuery取消选择单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆