【问题标题】:How to check a radio button with jQuery?如何使用 jQuery 检查单选按钮?
【发布时间】:2011-08-05 16:09:34
【问题描述】:

我尝试使用 jQuery 检查单选按钮。这是我的代码:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

还有 JavaScript:

jQuery("#radio_1").attr('checked', true);

不起作用:

jQuery("input[value='1']").attr('checked', true);

不起作用:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

不起作用:

你还有别的想法吗?我错过了什么?

【问题讨论】:

  • 感谢您的回复!我发现了问题。实际上,前两种方法是有效的。关键是我使用 jqueryUI 将一组 3 个单选按钮转换为使用以下代码设置的按钮:jQuery("#type").buttonset();但是在检查收音机之前进行此更改会破坏收音机(不知道为什么)。最后,我在检查收音机后调用了 buttonset 调用,它工作得无可挑剔。

标签: javascript jquery radio-button


【解决方案1】:

最短

radio_1.checked

checkBtn.onclick = e=> {
  console.log( radio_1.checked );
}
Select first radio and click button
<!-- Question html -->
<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

<!-- Test html -->
<button id="checkBtn">Check</button>

【讨论】:

  • 有些人不加评论就给减分 - 但这个简短的解决方案确实有效
【解决方案2】:

此答案感谢 a comment 中的 Paul LeBeau。我想我会把它写成一个正确的答案,因为令人惊讶的是没有一个。

唯一对我有用的东西(jQuery 1.12.4,Chrome 86)是:

$(".js-my-radio-button").trigger("click");

这可以满足我的所有需求 - 更改看起来被选中的单选按钮(视觉和编程)并触发单选按钮上的事件,例如 change

按照其他答案的建议设置“checked”属性不会改变为我选择的单选按钮。

【讨论】:

    【解决方案3】:

    使用 prop() 方法

    来源Link

    <p>
        <h5>Radio Selection</h5>
    
        <label>
            <input type="radio" name="myRadio" value="1"> Option 1
        </label>
        <label>
            <input type="radio" name="myRadio" value="2"> Option 2
        </label>
        <label>
            <input type="radio" name="myRadio" value="3"> Option 3
        </label>
    </p>
    
    <p>
        <button>Check Radio Option 2</button>
    </p>
    
    
    <script>
        $(function () {
    
            $("button").click(function () {
                $("input:radio[value='2']").prop('checked',true);
            });
    
        });
    </script>
    

    【讨论】:

      【解决方案4】:

      我使用 jquery-1.11.3.js

      基本启用和禁用

      提示1:(单选按钮类型常用Disable & Enable)

      $("input[type=radio]").attr('disabled', false);
      $("input[type=radio]").attr('disabled', true); 
      

      提示2:(ID选择器使用prop()或attr())

      $("#paytmradio").prop("checked", true);
      $("#sbiradio").prop("checked", false);
      
      jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
      jQuery("#sbiradio").attr('checked', false);
      

      提示3:(类选择器使用prop()或arrt())

      $(".paytm").prop("checked", true);
      $(".sbi").prop("checked", false);
      
      jQuery(".paytm").attr('checked', 'checked'); // or true
      jQuery(".sbi").attr('checked', false);
      

      其他提示

      $("#paytmradio").is(":checked")   // Checking is checked or not
      $(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled
      
      $('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
       $("input:checked", "#paytmradio").val() // get the checked value
      

      index.html

      <div class="col-md-6">      
          <label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
          <div id="paymenttype" class="form-group" style="padding-top: inherit;">
              <label class="radio-inline" class="form-control"><input  type="radio" id="paytmradio"  class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
              <label class="radio-inline" class="form-control"><input  type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
          </div>
      </div>
      

      【讨论】:

        【解决方案5】:

        如果您不想为这么简单的事情包含一个像 jQuery 这样的大型库,这里有一个使用内置 DOM 方法的替代解决方案:

        // Check checkbox by id:
        document.querySelector('#radio_1').checked = true;
        
        // Check checkbox by value:
        document.querySelector('#type > [value="1"]').checked = true;
        
        // If this is the only input with a value of 1 on the page, you can leave out the #type >
        document.querySelector('[value="1"]').checked = true;
        <form>
            <div id='type'>
                <input type='radio' id='radio_1' name='type' value='1' />
                <input type='radio' id='radio_2' name='type' value='2' />
                <input type='radio' id='radio_3' name='type' value='3' /> 
            </div>
        </form>

        【讨论】:

          【解决方案6】:

          令人惊讶的是,尽管有 cmets,但最受欢迎和接受的答案却忽略了触发适当的事件。 确保调用.change(),否则所有“on change”绑定都会忽略此事件。

          $("#radio_1").prop("checked", true).change();
          

          【讨论】:

            【解决方案7】:

            另外可以检查元素是否被选中:

            if ($('.myCheckbox').attr('checked'))
            {
               //do others stuff
            }
            else
            {
               //do others stuff
            }
            

            您可以检查未检查的元素:

            $('.myCheckbox').attr('checked',true) //Standards way
            

            您也可以这样取消选中:

            $('.myCheckbox').removeAttr('checked')
            

            您可以检查单选按钮:

            对于等于或高于 (>=) 1.6 的 jQuery 版本,请使用:

            $("#radio_1").prop("checked", true);
            

            对于 (

            $("#radio_1").attr('checked', 'checked');
            

            【讨论】:

              【解决方案8】:

              attr 接受两个字符串。

              正确的做法是:

              jQuery("#radio_1").attr('checked', 'true');
              

              【讨论】:

                【解决方案9】:

                对于等于或高于 (>=) 1.6 的 jQuery 版本,请使用:

                $("#radio_1").prop("checked", true);
                

                对于 (

                $("#radio_1").attr('checked', 'checked');
                

                提示:之后您可能还想在单选按钮上致电click()change()查看 cmets 了解更多信息。

                【讨论】:

                • 在 jQuery 1.9 或更高版本中,此解决方案将不起作用。使用 $("#radio_1").prop("checked", true);而是。
                • 在末尾添加.change() 有助于触发页面上的任何其他事件。
                • 如果您希望单选组中的其他单选按钮正确更新,请使用$("#radio_1").prop("checked", true).trigger("click");
                【解决方案10】:

                试试这个

                $(document).ready(function(){
                    $("input[name='type']:radio").change(function(){
                        if($(this).val() == '1')
                        {
                          // do something
                        }
                        else if($(this).val() == '2')
                        {
                          // do something
                        }
                        else if($(this).val() == '3')
                        {
                          // do something
                        }
                    });
                });
                

                【讨论】:

                  【解决方案11】:

                  以防万一有人在使用 jQuery UI 时尝试实现此目的,您还需要刷新 UI 复选框对象以反映更新后的值:

                  $("#option2").prop("checked", true); // Check id option2
                  $("input[name='radio_options']").button("refresh"); // Refresh button set
                  

                  【讨论】:

                    【解决方案12】:

                    用例子试试这个

                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <form id="myForm">
                    <input type="radio" name="radio" value="first"/> 1 <br/>
                    <input type="radio" name="radio" value="second"/> 2 <br/>
                    </form>
                    
                    
                    <script>
                    $(document).ready(function () {
                        $('#myForm').on('click', function () {
                            var value = $("[name=radio]:checked").val();
                    
                            alert(value);
                        })
                    });
                    </script>
                    

                    【讨论】:

                      【解决方案13】:

                      我使用这个代码:

                      对不起英语。

                      var $j = jQuery.noConflict();
                      
                      $j(function() {
                          // add handler
                          $j('#radio-1, #radio-2').click(function(){
                      
                              // find all checked and cancel checked
                              $j('input:radio:checked').prop('checked', false);
                      
                              // this radio add cheked
                              $j(this).prop('checked', true);
                          });
                      });
                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                      <fieldset class="section">
                        <legend>Radio buttons</legend>
                        <label>
                          <input type="radio" id="radio-1" checked>
                          Option one is this and that&mdash;be sure to include why it's great
                        </label>
                        <br>
                        <label>
                          <input type="radio" id="radio-2">
                          Option two can be something else
                        </label>
                      </fieldset>

                      【讨论】:

                        【解决方案14】:
                        function rbcitiSelction(e) {
                             debugger
                            $('#trpersonalemail').hide();
                            $('#trcitiemail').show();
                        }
                        
                        function rbpersSelction(e) {
                            var personalEmail = $(e).val();
                            $('#trpersonalemail').show();
                            $('#trcitiemail').hide();
                        }
                        
                        $(function() {  
                            $("#citiEmail").prop("checked", true)
                        });
                        

                        【讨论】:

                          【解决方案15】:

                          是的,它对我很有用:

                          $("#radio_1").attr('checked', 'checked');
                          

                          【讨论】:

                            【解决方案16】:

                            我刚刚遇到类似的问题,一个简单的解决方案就是使用:

                            .click()
                            

                            如果您在调用函数后刷新收音机,任何其他解决方案都可以工作。

                            【讨论】:

                            • 调用点击有时在ie9中很头疼
                            【解决方案17】:

                            我们应该知道它是一个radio 按钮。所以请尝试以下代码。

                            $("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
                            

                            【讨论】:

                              【解决方案18】:

                              获取价值:

                              $("[name='type'][checked]").attr("value");
                              

                              设定值:

                              $(this).attr({"checked":true}).prop({"checked":true});
                              

                              单选按钮单击添加属性检查:

                              $("[name='type']").click(function(){
                                $("[name='type']").removeAttr("checked");
                                $(this).attr({"checked":true}).prop({"checked":true});
                              });
                              

                              【讨论】:

                                【解决方案19】:

                                试试这个。

                                在这个例子中,我用它的输入名称和值来定位它

                                $("input[name=background][value='some value']").prop("checked",true);
                                

                                很高兴知道:在多字值的情况下,它也会因为撇号而起作用。

                                【讨论】:

                                  【解决方案20】:

                                  试试这个:

                                  $("input[name=type]").val(['1']);
                                  

                                  http://jsfiddle.net/nwo706xw/

                                  【讨论】:

                                  • 重要的是.val(['1']) 不是.val('1')
                                  【解决方案21】:

                                  试试这个:

                                  $(document).ready(function(){
                                    $("#Id").prop("checked", true).checkboxradio('refresh');
                                  });
                                  

                                  【讨论】:

                                  • 如果不包含 checkboxradio 插件的文件,这将无法工作,当您可以使用 jQuery 的内置函数来完成此操作时,这是没有意义的(请参阅接受的答案)。
                                  【解决方案22】:
                                  $("input[name=inputname]:radio").click(function() {
                                      if($(this).attr("value")=="yes") {
                                          $(".inputclassname").show();
                                      }
                                      if($(this).attr("value")=="no") {
                                          $(".inputclassname").hide();
                                      }
                                  });
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    我有一些相关的例子需要增强,如果我想添加一个新的条件,比如说,如果我想在我点击项目状态值后隐藏配色方案,除了 Pavers 和 Paving Slabs。

                                    示例在这里:

                                    $(function () {
                                        $('#CostAnalysis input[type=radio]').click(function () {
                                            var value = $(this).val();
                                    
                                            if (value == "Supply & Lay") {
                                                $('#ul-suplay').empty();
                                                $('#ul-suplay').append('<fieldset data-role="controlgroup"> \
                                    

                                    http://jsfiddle.net/m7hg2p94/4/

                                    【讨论】:

                                      【解决方案24】:

                                      上面的解决方案有时不起作用,那么您可以尝试以下方法:

                                      jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
                                      jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
                                      

                                      您可以尝试的另一种方法是:

                                      jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);
                                      

                                      【讨论】:

                                      • Uniform 是一个让表单更漂亮的 jQuery 插件,但它通过添加额外的元素来做到这一点。每当我更新选中的值时,额外的元素状态不会更新,从而导致不可见的输入未被选中,但具有看起来已选中的可见背景元素。 jQuery.uniform.update() 是解决方案!
                                      【解决方案25】:

                                      如果属性name 不起作用,请不要忘记id 仍然存在。此答案适用于想要在此处定位 id 的人。

                                      $('input[id=element_id][value=element_value]').prop("checked",true);
                                      

                                      因为属性name 对我不起作用。确保不要用双引号/单引号包围 idname

                                      干杯!

                                      【讨论】:

                                        【解决方案26】:

                                        试试这个

                                         $("input:checked", "#radioButton").val()
                                        

                                        如果选中返回True 如果未选中返回False

                                        jQuery v1.10.1
                                        

                                        【讨论】:

                                          【解决方案27】:

                                          $.prop 方式更好:

                                          $(document).ready(function () {                            
                                              $("#radio_1").prop('checked', true);        
                                          });
                                          

                                          你可以像下面这样测试它:

                                          $(document).ready(function () {                            
                                              $("#radio_1, #radio_2", "#radio_3").change(function () {
                                                  if ($("#radio_1").is(":checked")) {
                                                      $('#div1').show();
                                                  }
                                                  else if ($("#radio_2").is(":checked")) {
                                                      $('#div2').show();
                                                  }
                                                  else 
                                                      $('#div3').show();
                                              });        
                                          });
                                          

                                          【讨论】:

                                            【解决方案28】:

                                            试试这个。

                                            使用 Value 来检查单选按钮。

                                            $('input[name=type][value=2]').attr('checked', true); 
                                            

                                            或者

                                            $('input[name=type][value=2]').attr('checked', 'checked');
                                            

                                            或者

                                            $('input[name=type][value=2]').prop('checked', 'checked');
                                            

                                            使用 ID 来检查单选按钮。

                                            $('#radio_1').attr('checked','checked');
                                            

                                            或者

                                            $('#radio_1').prop('checked','checked');
                                            

                                            【讨论】:

                                              【解决方案29】:

                                              简短易读的选项:

                                              $("#radio_1").is(":checked")
                                              

                                              它返回真或假,所以你可以在“if”语句中使用它。

                                              【讨论】:

                                              • 谢谢!这是我一直在寻找的,但是(仅供参考)OP 询问如何设置单选按钮,而不是获取值。 (“检查”一词使问题变得混乱。)
                                              【解决方案30】:

                                              试试这个

                                              var isChecked = $("#radio_1")[0].checked;
                                              

                                              【讨论】:

                                                猜你喜欢
                                                • 2012-02-02
                                                • 1970-01-01
                                                • 1970-01-01
                                                • 2019-05-29
                                                • 1970-01-01
                                                • 2016-05-08
                                                • 2016-08-17
                                                • 1970-01-01
                                                • 1970-01-01
                                                相关资源
                                                最近更新 更多