Javascript/JQuery 取消选择单选按钮

Javascript/ JQuery Deselecting radio buttons(Javascript/JQuery 取消选择单选按钮)
本文介绍了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.

您似乎无法使用 return falsee.preventDefault() 来阻止单选按钮的默认行为,因为单选按钮总是在点击处理程序被触发.解决此问题的一种方法是向单选按钮添加一个单独的类并将其用作您的指示器.

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 取消选择单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)