【问题标题】:jQuery check/uncheck radio button onclickjQuery 选中/取消选中单选按钮 onclick
【发布时间】:2011-09-05 16:54:35
【问题描述】:

我有此代码来检查/取消选中单选按钮 onclick。

我知道这对 UI 不利,但我需要这个。

$('#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。

【问题讨论】:

  • 应该注意的是,如果您还根据它的选中状态对这个收音机做一些事情,您可能会在 onclick 事件上得到误导性的“选中”值。一种解决方案是在 mousedown 上分配您要分配给它的值(与它的值相反)在节点上的变量中,例如 this.__rval 并检查它是否存在于您的 onclick 处理程序中。如果它存在,您就知道其中的值是正确的,尽管 this.checked 可能即将更改。

标签: javascript jquery radio


【解决方案1】:

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

$("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');
  }
});

【讨论】:

  • 这正是我所需要的(谢谢)。我在jsfiddle.net/dan74/6KYVP 添加了一个演示 - 如果默认选中收音机,则需要单击两次以取消选中(我可以忍受),否则收音机的行为与预期一样(可以取消选中)
  • 需要更正... $("input[name='" + name + "']:radio").attr('previousValue', false); ...注意 +name+ ... ' " + name + " ' 周围的单引号
【解决方案2】:

如果您只想使用复选框进行检查,请不要担心使用 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 设置为复选框上的属性来工作,因为我认为prop 在1.3.2 中不受支持。您也可以在作用域变量中执行此操作,因为有些人不喜欢在字段上设置随机属性。 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'));
    });
};

【讨论】:

  • 我最喜欢的检查 'checked' 状态的方法是使用 $(this).is(':checked')
  • 注意到 .attr() 不适用于较新版本的 jQuery(本例中为 1.9.1)。更改为 $(this).prop("checked");如果你想走这条路。
  • 如果您有多个单选按钮(这是使用单选按钮的全部目的),您的单选按钮示例将无法正常工作。 Jurrie 的回答更接近于解决方案。
  • @JoshStodola 谢谢,现在已修复。
  • var value = $('#radGroup').is(':checked') ? 1 : 0;
【解决方案3】:

您设置的不是检查值:

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; 
        }
    });
});

P.S.: 对于 jquery ,应使用 $().attr 而不是 $().prop

演示:jsFiddle

【讨论】:

  • 是的,它不起作用,因为每当您单击时,都会将其状态设置为 checked=true(单击是检查单选按钮)
  • 你必须将它的状态存储在一个全局变量中并检查它。查看我的编辑。
  • 为什么你会有一个只有一个单选按钮的“工作解决方案”?使用一个单选按钮是没有意义的,总会有多个选择...
  • @JoshStodola,不用生气,问题是关于一个单选按钮。但是,您对多个单选按钮的解决方案是正确的。答案已更新。
【解决方案4】:

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

$(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

享受吧。

【讨论】:

  • 有效,但我必须刷新按钮才能更新按钮...在末尾添加了这个 `$(this).button('refresh');`
【解决方案5】:

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

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

$("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);
});

【讨论】:

  • 最后,唯一正确解决问题的解决方案:当点击事件发生时,收音机已经检查,使得所有这些依赖于检查状态的解决方案绝对无用
【解决方案6】:

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

您可以使用将单选按钮放在标签或按钮标签内并做一些好事。

【讨论】:

    【解决方案7】:

            $(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】:

      -- 编辑--

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

      var $radio = $("#radioinstant"),
          isChecked = $radio.attr("checked");
      
      $radio.click(function() {
      
          isChecked = !isChecked;
          $(this).attr("checked", isChecked);
      
      });
      

      【讨论】:

      • 这仅适用于第一次。但是,如果用户决定再次检查它,它将无法正常工作。用户在做事时可能会改变他们的决定。我怎么能说 onclick 来检查它是否未选中,如果它每次都选中则取消选中它?谢谢
      • 我不确定您要完成什么?您是否试图强制无线电输入像复选框输入一样?
      【解决方案9】:

      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】:

        在测试了上述一些对我来说不是 100% 的解决方案后,我决定创建自己的解决方案。单击单选按钮后,它会创建新的单击侦听器:

        /**
         * 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();
        

        【讨论】:

          【解决方案11】:

          $(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"));
          });
          

          });

          【讨论】:

            【解决方案12】:

            迭戈P,

            我遇到了同样的麻烦,直到我意识到在删除该属性之前,该框上的检查才会生效。这意味着即使检查值被设为假,它也会保留在那里。

            因此使用 removeAttr() 函数并删除选中的属性,它肯定会工作。

            【讨论】:

              【解决方案13】:

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

              <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>
              

              【讨论】:

                【解决方案14】:

                此功能将为所有单选按钮添加选中/取消选中

                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
                
                });
                });
                

                【讨论】:

                  【解决方案15】:

                  我把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"));
                          }
                  
                      });
                  

                  【讨论】:

                    【解决方案16】:

                    我建议这样做:

                    $('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" />
                    

                    【讨论】:

                      【解决方案17】:

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

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

                      代码

                              $('#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);
                              }
                      

                      【讨论】:

                        【解决方案18】:

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

                        • 选项 1 将显示两个单选按钮,其中第一个单选按钮被选中
                        • 选项 2 将显示第二个单选按钮并被选中。

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

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

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

                        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】:

                          这是一个简单的解决方案,希望对您有所帮助。这是一个改进答案的简单示例。

                          $('[type="radio"]').click(function () {
                          
                                      if ($(this).attr('checked')) {
                          
                                          $(this).removeAttr('checked');
                                          $(this).prop('checked',false);
                          
                                      } else {
                          
                                          $(this).attr('checked', 'checked');
                          
                                      }
                                  });
                          

                          Demo 抱歉为时已晚.. :)

                          【讨论】:

                            【解决方案20】:

                            最后一个解决方案对我有用。我遇到了 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();
                            
                            }
                            

                            【讨论】:

                              【解决方案21】:

                              我从这个问题尝试的解决方案对我不起作用。在部分有效的答案中,我仍然发现我必须单击以前未选中的单选按钮两次才能再次选中它。我目前正在使用 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');
                                  }
                              });
                              

                              【讨论】:

                                【解决方案22】:

                                如果您在单击时使用并且只检查是否选中了收音机然后取消选择,您将永远不会选中收音机。所以也许最简单的方法是使用这样的类名:

                                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
                                    }
                                

                                【讨论】:

                                  【解决方案23】:

                                  最简单的解决方案。对于 Radio 和 Checkboxes。

                                  $('body').on('click', 'input[type="checkbox"]', function(){
                                      if ($(this).attr('checked')){
                                          $( this ).attr( 'checked', false);
                                      } else {
                                          $( this ).attr( 'checked', true);
                                      }
                                  });
                                  $('body').on('click', 'input[type="radio"]', function(){
                                      var name = $(this).attr('name');
                                      $("input[name="+name+"]:radio").attr('checked', false);
                                      $( this ).attr( 'checked', true);
                                  });
                                  

                                  【讨论】:

                                    【解决方案24】:

                                    我认为这是最短的方法。我在 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)
                                    })
                                    

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

                                    【讨论】:

                                      【解决方案25】:

                                      这个帖子中的一些答案对我很有帮助,我想我会使用 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');
                                          });
                                      }
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2018-08-29
                                        • 2018-09-04
                                        • 2011-07-17
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2012-01-23
                                        相关资源
                                        最近更新 更多