jQuery检查/取消选中单选按钮onclick

时间:2011-05-31 18:05:56

标签: javascript jquery radio

我有这个代码来检查/取消选中单击按钮。

我知道它对用户界面不好,但我需要这个。

$('#radioinstant').click(function() {     
  var checked = $(this).attr('checked', true);
  if(checked){ 
    $(this).attr('checked', false);
  }
  else{ 
    $(this).attr('checked', true);
  }
});

上述功能无效。

如果我点击按钮,则没有任何变化。它仍然是检查。为什么?错误在哪里?我不是jQuery专家。我在jQuery 1.3.2

要清楚#radioinstant是单选按钮的ID。

25 个答案:

答案 0 :(得分:37)

我已经扩展了以前的建议。 这适用于我,多个无线电通过相同的名称耦合。

$("input[type='radio']").click(function()
{
  var previousValue = $(this).attr('previousValue');
  var name = $(this).attr('name');

  if (previousValue == 'checked')
  {
    $(this).removeAttr('checked');
    $(this).attr('previousValue', false);
  }
  else
  {
    $("input[name="+name+"]:radio").attr('previousValue', false);
    $(this).attr('previousValue', 'checked');
  }
});

答案 1 :(得分:23)

如果你想要做的就是有一个复选框来检查,不要担心用JQuery做这件事。这是点击复选框的默认功能。但是,如果您想要执行其他操作,可以使用JQuery添加它们。在jQuery 1.9之前,您可以使用$(this).attr('checked');来获取值而不是$(this).attr('checked', true);,因为第二个将设置值。

Here是一个小提示演示,显示默认复选框功能与您使用JQuery的操作。

注意:在JQuery 1.6之后,你应该在所有三个地方使用$(this).prop;而不是$(this).attr(感谢@Whatevo指出这一点和see here for further details) 。

<强>更新

抱歉,错过了必须是单选按钮的要求。您仍然可能需要考虑复选框,但here是无线电输入版本的更新代码。它的工作原理是将previousValue设置为复选框上的属性,因为我认为1.3.2中不支持prop。您也可以在范围变量中执行此操作,因为有些人不喜欢在字段上设置随机属性。 Here是新的例子。

更新2:

正如Josh指出的那样,之前的解决方案只能使用一个单选按钮。这是一个功能,使一组无线电可以通过其名称取消选择,并fiddle

var makeRadiosDeselectableByName = function(name){
    $('input[name=' + name + ']').click(function() {
        if($(this).attr('previousValue') == 'true'){
            $(this).attr('checked', false)
        } else {
            $('input[name=' + name + ']').attr('previousValue', false);
        }

        $(this).attr('previousValue', $(this).attr('checked'));
    });
};

答案 2 :(得分:13)

您可以使用以下方式设置检查值:

var checked = $(this).attr('checked', true);

要正确得到它:

var checked = $(this).attr('checked');

一种工作解决方案(具有不同值的多个单选按钮):

// select radio buttons group (same name)
var radioButtons = $("input[type='radio'][name='rr']");
// save initial ckecked states
var radioStates = {};
$.each(radioButtons, function(index, rd) {
    radioStates[rd.value] = $(rd).is(':checked');
});

// handle click event
radioButtons.click(function() {

    // check/unchek radio button
    var val = $(this).val();  
    $(this).prop('checked', (radioStates[val] = !radioStates[val]));    

    // update other buttons checked state
    $.each(radioButtons, function(index, rd) {
        if(rd.value !== val) {
            radioStates[rd.value] = false; 
        }
    });
});
对于jquery&lt;应该使用

P.S。: $().attr代替$().prop 1.6

演示:jsFiddle

答案 3 :(得分:12)

最佳和最短的解决方案。它适用于任何一组无线电(具有相同的名称)。

$(document).ready(function(){
    $("input:radio:checked").data("chk",true);
    $("input:radio").click(function(){
        $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");
        $(this).data("chk",!$(this).data("chk"));
        $(this).prop("checked",$(this).data("chk"));
        $(this).button('refresh'); // in case you change the radio elements dynamically
    });
});

更多信息,here

享受。

答案 4 :(得分:2)

我相信这就是问题:如果您有多个单选按钮,并且其中一个单击按钮,则无法取消选择所有单选按钮。我们需要的是“无或只有一个”选择器,因此复选框不合适。你可以有一个“清除”按钮或类似的东西来取消选择所有,但是只需单击所选的单选按钮取消选择它并返回到“无”状态就好了,所以你不要弄乱你的用户界面一个额外的控制。

使用点击处理程序的问题是,在调用它时,已经选中了单选按钮。您不知道这是初始点击还是第二次点击已经选中的单选按钮。所以我使用了两个事件处理程序,mousedown来设置上一个状态,然后是上面使用的click处理程序:

$("input[name=myRadioGroup]").mousedown(function () 
{
    $(this).attr('previous-value', $(this).prop('checked'));
});

$("input[name=myRadioGroup]").click(function () 
{
    var previousValue = $(this).attr('previous-value');

    if (previousValue == 'true')
        $(this).prop('checked', false);
});

答案 5 :(得分:2)

toggleAttr()this very nice and tiny plugin提供。

示例代码

$('#my_radio').click(function() {
    $(this).toggleAttr('checked');
});

/**
 * toggleAttr Plugin
 */
jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
        var $this = $(this);
        $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
};

更有趣,demo

您可以使用标签或按钮标签内的单选按钮,并做一些不错的事情。

答案 6 :(得分:1)

测试了上述一些对我不起作用的解决方案,我决定创建自己的解决方案。单击单选按钮后,它会创建新的单击侦听器:

/**
 * Radio select toggler
 * enables radio buttons to be toggled when clicked
 * Created by Michal on 09/05/2016.
 */

var radios = $('input[type=radio]');

/**
 * Adds click listeners to all checkboxes to unselect checkbox if it was checked already
 */
function updateCheckboxes() {
    radios.unbind('click');
    radios.filter(':checked').click(function () {
        $(this).prop('checked', false);
    });
    radios.click(function () {
        updateCheckboxes();
    });
}

updateCheckboxes();

答案 7 :(得分:1)

        $(document).on("click", "input[type='radio']", function(e) {
            var checked = $(this).attr("checked");
            if(!checked){
                $(this).attr("checked", true);
            } else {
                $(this).removeAttr("checked");
                $(this).prop("checked", false);
            }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" id="radio" /> <label for="radio">Radio</label>

答案 8 :(得分:1)

(文档)$。就绪(函数(){     $(&#34;输入:无线​​电:检查&#34)。数据(&#34; CHK&#34;,TRUE);

remuneração\D*(\d[\d.,]+\b *(?:\€|EUR)|(?:\€|EUR) *\d[\d.,]+\b)

});

答案 9 :(得分:1)

Jurrie的答案改进版

$('#myRadio').off('click').on('click', function() {
  if ($(this).data('checked')) {
    $(this).removeAttr('checked');
    $(this).data('checked', false);
  } else {
    $(this).data('checked', true);
  }
});

Live Demo

答案 10 :(得分:0)

最简单的解决方案。对于单选框和复选框。

Task aTask = A.Play(cancel);
Task bTask = B.Play(cancel);

// will return only when A is complete. 
await aTask;

// await bTask seperately. 

答案 11 :(得分:0)

最后一个解决方案是适合我的解决方案。我遇到了Undefined和object对象的问题,或者总是返回false然后总是返回true,但这个解决方案在检查和取消检查时都有效。

此代码显示单击时的字段,并在取消选中时隐藏字段:

$("#new_blah").click(function(){
   if ($(this).attr('checked')) {

            $(this).removeAttr('checked');
    var radioValue = $(this).prop('checked',false);
    // alert("Your are a rb inside 1- " + radioValue);
    // hide the fields is the  radio button is no     
    $("#new_blah1").closest("tr").hide();
    $("#new_blah2").closest("tr").hide();

    } 
    else {

    var radioValue =  $(this).attr('checked', 'checked');
    // alert("Your are a rb inside 2 - " + radioValue);
    // show the fields   when radio button is set to  yes
    $("#new_blah1").closest("tr").show();
    $("#new_blah2").closest("tr").show();

}

答案 12 :(得分:0)

我从这个问题尝试的解决方案对我不起作用。在部分工作的答案中,我仍然发现我必须再次点击之前未选中的单选按钮才能再次检查它。我目前正在使用jQuery 3 +。

在尝试使用数据属性或其他属性使其工作之后,我终于通过使用类来找出解决方案。

对于您选中的收音机输入,请为其指定班级checked,例如:

<input type="radio" name="likes_cats" value="Meow" class="checked" checked>

这是jQuery:

$('input[type="radio"]').click(function() {
    var name = $(this).attr('name');

    if ($(this).hasClass('checked')) {
        $(this).prop('checked', false);
        $(this).removeClass('checked');
    }
    else {
        $('input[name="'+name+'"]').removeClass('checked');
        $(this).addClass('checked');
    }
});

答案 13 :(得分:0)

如果您在点击时使用并且仅检查是否已选中无线电然后取消选择,则您将永远不会检查无线电。所以最简单的方法是使用这样的类名:

if($(this).hasClass('alreadyChecked')) {//it is already checked
        $('.myRadios').removeClass('alreadyChecked');//remove from all radios
        $(this).prop('checked', false);//deselect this
    }
    else {
        $('.myRadios').removeClass('alreadyChecked');//remove from all
        $(this).addClass('alreadyChecked');//add to only this
    }

答案 14 :(得分:0)

我有一个相关但不同的场景。以下是我正在做的事情:

注意:选择主单选按钮时,选择/取消选择“containerRadio”类的所有单选按钮的代码。

<强> CODE

        $('#selectAllWorkLot').click (function ()
        {

              var previousValue = $(this).attr('previousValue');

              if (previousValue == 'checked')
              {
                resetRadioButtonForSelectAll();

                //Unselect All
                unSelectAllContainerRadioButtons();
              }
              else
              {
                $(this).attr('previousValue', 'checked');

                //Select All
                selectAllContainerRadioButtons();
              }
        });


        function resetRadioButtonForSelectAll()
        {
            $('#selectAllWorkLot').removeAttr('checked');
            $('#selectAllWorkLot').attr('previousValue', false);
            //$('#selectAllWorkLot').prop('checked', false);
        }


        function selectAllContainerRadioButtons()
        {
            $('.containerRadio').prop('checked', true);
        }

        function unSelectAllContainerRadioButtons()
        {
            $('.containerRadio').prop('checked', false);
        }

答案 15 :(得分:0)

我认为这是最短的方法。我在Chrome和MS Edge上进行了测试。

$(document).on('click', 'input:radio', function () {
    var check = $(this).attr('checked')
    if (check) $(this).removeAttr('checked').prop('checked',false)
    else $(this).attr('checked', true).prop('checked',true)
})

这段代码也可用于已加载AJAX 的内容。

或者,您也可以使用

$(document).on('click mousedown', 'input:radio', function (e) {
    e.preventDefault()
    if ($(this).prop('checked')) $(this).prop('checked', false)
    else $(this).prop('checked', true)
})

这样会更好,没有任何例外。

答案 16 :(得分:0)

该线程中的一些答案对我有帮助,我想我会使用 jQuery 和 HTML 5 分享更新的答案:

<input type="radio" name="myRadioGroupName" value="true" checked="false" data-checked-before="false"/>
<input type="radio" name="myRadioGroupName" value="false" checked="false" data-checked-before="false"/>

$(function () {
    // Allows us to easily uncheck radio buttons.
    $("input[type='radio']").click(function (e) {
        var htmlName = $(this).attr('name');
        var radio = $("input[name='" + htmlName + "'][value='" + $(this).val() + "']");
        // Since onclick() and preventDefault() work differently for radio buttons, we
        // have to wait until after all the values have been set,
        // and then set them to what we want.
        setTimeout(function () {
            // $(radio).is(":checked") will always return true, so we have to
            // set our own HTML property.
            if ($(radio).attr('data-checked-before') == 'true') {
                $(radio).prop("checked", false);
            }
            ClearCheckedBefore(htmlName);
            // Save the state for the next time we look at it.
            $(radio).attr('data-checked-before', $(radio).is(':checked').toString());
        }, 5);
    });
});

// Marks all data-checked-before attributes to false, so the
// if-statements in the setTimeout function don't get confused.
function ClearCheckedBefore(htmlName) {
    $("input[name='" + htmlName + "']").each(function (index, value) {
        $(value).attr('data-checked-before', 'false');
    });
}

答案 17 :(得分:0)

这里是简单的解决方案,我希望它能帮到你。这是一个改善答案的简单例子。

$('[type="radio"]').click(function () {

            if ($(this).attr('checked')) {

                $(this).removeAttr('checked');
                $(this).prop('checked',false);

            } else {

                $(this).attr('checked', 'checked');

            }
        });

Demo 对不起太晚了.. :)

答案 18 :(得分:0)

我遇到了一个相关的问题 - 我必须根据下拉列表中的选择从下拉列表中打开一个对话框,我将显示一个或两个单选按钮。一次只能激活一个单选按钮。

  • 选项1将显示两个选择了第一个无线电的单选按钮
  • 选项2将显示第二个单选按钮并已选中。

脚本工作一段时间它会注入已选中但复选框仍未选中

我去了jQuery .prop(),似乎jquery .prop() .attr()在使用attr或prop时对单选按钮有一些复杂性。所以我所做的就是根据选择值触发单击单选按钮。

这解决了使用attr或prop或使用非冗长代码的需要。

myForm = $("#myForm");

if (argument === 'multiple') {
            myForm.find('#radio1').parent('li').hide();
            myForm.find('#radio2').trigger('click');
    }
    else{
        myForm.find('#radio1').trigger('click');
         myForm.find('#radio1').parent('li').show();
    }

不确定这是否是最佳做法,但它 - 像魅力一样工作

答案 19 :(得分:0)

我会建议:

$('input[type="radio"].toggle').click(function () {
    var $rb = $(this);

    if ($rb.val() === 'on') {
        $rb.val('off');
        this.checked = false;
    }
    else {
        $rb.val('on');
        this.checked = true;
    }
});

您的HTML将如下所示:

<input type="radio" class="toggle" value="off" />

答案 20 :(得分:0)

我拿了https://stackoverflow.com/a/13575528/80353并按照这个改编了

$(document).ready(function() {

        $('body').on('click', 'input[type="radio"]', function() {
            changeCheckedAttributes($(this));
        });
        function changeCheckedAttributes(elt) {
            $("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeData("chk");
            $("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeAttr("checked");
            $("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).prop("checked", false);
            $(elt).data("chk",!$(elt).data("chk"));
            $(elt).prop("checked", true);
            $(elt).attr("checked", $(elt).data("chk"));
        }

    });

答案 21 :(得分:0)

此功能会向所有单选按钮添加检查/未选中

jQuery(document).ready(function(){
jQuery(':radio').click(function()
{
if ((jQuery(this).attr('checked') == 'checked') && (jQuery(this).attr('class') == 'checked'))
{   
    jQuery(this).attr('class','unchecked');
    jQuery(this).removeAttr('checked');
} else {
jQuery(this).attr('class','checked');
}//or any element you want

});
});

答案 22 :(得分:0)

如果您仍然需要更多答案,我发现这适用于所有单选按钮:

<script type="text/javascript">
        jQuery(document).ready(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);    
                        });

                    });
        });
</script>

答案 23 :(得分:0)

DiegoP,

我遇到了同样的麻烦,直到我意识到盒子上的检查没有消失,直到属性被删除。这意味着即使检查值为false,它也会保留在那里。

因此使用removeAttr()函数并删除已检查的attrib并且它将完全正常工作。

答案 24 :(得分:0)

- 编辑 -

看起来您的代码似乎强制无线电输入的行为类似于复选框输入。您可能会想到只使用复选框输入而不需要jQuery。但是,如果要强制,就像@manji所说的那样,您需要将值存储在click处理程序之外,然后在每次单击时将其设置为与当时相反的值。 @ manji的答案是正确的,我只想补充一点,你应该缓存jQuery对象而不是重新查询DOM:

var $radio = $("#radioinstant"),
    isChecked = $radio.attr("checked");

$radio.click(function() {

    isChecked = !isChecked;
    $(this).attr("checked", isChecked);

});