【问题标题】:.prop() not doing anything to target radio buttons.prop() 没有针对单选按钮做任何事情
【发布时间】:2018-11-29 10:53:14
【问题描述】:

我正在尝试取消选中一组 2 个单选按钮。

         <label>Yes 
            <input type="radio" value="true"  name="gasCustomer">
         </label>
         <label>No  
            <input type="radio" value="false"  name="gasCustomer">
         </label>

$(function () {
    $('[name="electricCustomer"]').click(function () {            
            $('[name="gasCustomer"]').prop('checked', false);
    });
});

我尝试过使用.prop('checked', false);,但这没有任何作用,也没有引发控制台错误。

我似乎也无法通过提供每个选项和 id 并执行以下操作来将所选选项更改为另一个选项:

             <label>Yes 
                <input type="radio" value="true"  name="gasCustomer" id="gasCYes">
             </label>
             <label>No  
                <input type="radio" value="false"  name="gasCustomer" id="gasCNo">
             </label>

   $(function () {
            $('[name="electricCustomer"]').click(function () { 
                    $("#gasCNo").prop('checked', true);
   });

【问题讨论】:

  • 是什么让您认为.prop("checked", false) 不起作用?您的单选按钮开始时未选中,这使它们未选中,因此很难看出区别。如果您确保其中一个开始检查,您会发现它有效:jsfiddle.net/60zdpn1b
  • 请用minimal reproducible example 更新您的问题,证明问题,最好是可运行 使用堆栈片段([&lt;&gt;] 工具栏按钮;here's how to do one)。跨度>
  • @T.J.Crowder ...我想从诸如单击另一个表单输入之类的功能中取消选中它们,我的问题与它们的加载状态无关。
  • 顺便说一句,为什么电力客户不能同时成为天然气客户?但我的猜测是,如果电动选项也是单选按钮,您需要绑定到它们的更改事件,因为您很可能单击它们的标签而不是实际输入

标签: javascript jquery radio-button prop


【解决方案1】:

使用 removeAttr 即可。请参阅下面的更新代码。

<div class="col-sm-9" id="gasCustomer">
     <div class="btn-group radio-group">
         <label class="btn btn-primary not-active">Yes 
            <input type="radio" value="true"  name="gasCustomer" id="gasCYes">
         </label>
         <label class="btn btn-primary not-active">No  
            <input type="radio" value="false"  name="gasCustomer" id="gasCNo">
         </label>
     </div>
 </div>


   $(function () {
        $('[name="electricCustomer"]').click(function () {            
            if ($(this).val() == 'true') {
                $("#electricAccountNumber").removeClass('hidden');
                $("#gasCNo").prop('checked', false).removeAttr('checked');
            }
        });
})

【讨论】:

    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多