Jquery 检查是否选中了单选按钮

Jquery check if radio button is checked

本文关键字:单选按钮 检查 是否 Jquery      更新时间:2023-09-26

如果选中单选按钮,我正在尝试取消选中它,同样检查一个单选按钮(如果未选中)。但是,它总是说它被检查了,而没有。

这是我的代码:

$('input[type=radio]').on('click', function() {
    if ($(this).attr('checked') == 'checked') {
        $(this).attr('checked', false);
    } else {
        $(this).attr('checked', true);
    }
});

上面的代码总是命中 if 的第一部分。我也试过

$(this).is(':checked') 

$(this).val() 

$(this).attr('checked') == true

但似乎没有任何效果。

我怎样才能让它工作?

这是小提琴希望这个myt有帮助:

<input type="radio" name="" value="1000" align="middle" id="private_contest">1000 is the value<br>
<input type="radio" name="" value="2000" align="middle" id="private_contest">2000 is the value

相关的jquery是:

$('input[type=radio]').on('click', function () {
                $(this).siblings().prop('checked', true);
                $(this).prop('checked', false);
        });

您需要删除选中的属性以取消选中,并添加属性以选中单选按钮。不要为其赋值:

<input type="radio" name="radio1">
<input type="radio" name="radio1" checked>

用:

$(this).addAttr("checked") 
$(this).removeAttr("checked")

这应该永远不会失败,但这是一种不同的方法。以父级为目标,并返回选中的无线电,而不是查看所有无线电。只是一个想法

var myRadio;
$('#radioParent input:radio').click(function() {
    myRadio = $(this).attr('id');
    //console.log(myRadio);
    //return myRadio;
});

我不确定为什么这会收到反对票。单选按钮的用法是,您可以有 0 或 1 个选项可供选择,如果需要选择 0 个或多个选项,则复选框列表是。但是,如果要撤消可选问题的单选按钮选择,该怎么办?

我通过在单选按钮上创建另一个称为"数据检查"的属性来解决此问题。

以下是实现:

$('input[type=radio]').on('click', function() {
    var radioButton = $(this);
    var radioButtonIsChecked = radioButton.attr('data-checked') == 'true';
    // set 'checked' to the opposite of what it is
    setCheckedProperty(radioButton, !radioButtonIsChecked);
    // you will have to define your own getSiblingsAnswers function
    //  as they relate to your application
    //  but it will be something similar to radioButton.siblings()
    var siblingAnswers = getSiblingAnswers(radioButton);
    uncheckSiblingAnswers(siblingAnswers);
});
function uncheckSiblingAnswers(siblingAnswers) {
    siblingAnswers.each(function() {
        setCheckedProperty($(this), false);
    });
}
function setCheckedProperty(radioButton, checked) {
    radioButton.prop('checked', checked);
    radioButton.attr('data-checked', checked);
}

在页面加载时,将数据检查属性设置为 true 或 false,具体取决于是否已选中该属性。

$(document).ready(function() {
    $('input[type=radio]').each(function () {
        var radioButton = $(this);
        var radioButtonIsChecked = radioButton.attr('checked') == 'checked';
        setCheckedProperty(radioButton, radioButtonIsChecked);
     });
 });