Javascript / JQuery取消选择单选按钮 [英] Javascript/ JQuery Deselecting radio buttons
问题描述
我有以下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屋!