【问题标题】:How to disable buttons based on which radio button is selected?如何根据选择的单选按钮禁用按钮?
【发布时间】:2017-06-30 20:51:03
【问题描述】:

我有 3 个 div 组,每个组包含一个单选按钮、一个标签和一个按钮。 我希望能够启用与所选单选按钮在同一组中的按钮,并禁用其他组中的按钮。

<div class="row">
  <div class="col-md-6">
    <!-- when this radio button is checked... -->
    <input id="input-1" type="radio" name="disable-button" checked="checked">
    <label for="input-1">Input 1</label>
    <!-- this button is enabled -->
    <button type="button">ADD</button>
    <!-- ...and vice versa -->
  </div>
  <div class="col-md-6">
    <!-- when this radio button is not checked... -->
    <input id="input-2" type="radio" name="disable-button">        
    <label for="input-2">Input 1</label>
    <!-- ...this button should be disabled -->
    <button type="button" disabled>ADD</button>
    <!-- ...and vice versa -->
  </div>
  <div class="col-md-6">
    <!-- when this radio button is not checked... -->
    <input id="input-3" type="radio" name="disable-button">
    <!-- ...this button should be disabled -->
    <label for="input-3">Input 1</label>
    <button type="button" disabled>ADD</button>
    <!-- ...and vice versa -->
  </div>
</div>

有没有办法通过 jQuery 做到这一点?

编辑:如果可能的话,我希望解决方案是动态的,以防我必须添加更多组。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    我会使用以下 jQuery 代码:

    $('input[type=radio]').change(function(){
      $('button').prop('disabled', true);
      $(this).parent().find('button').prop('disabled', false);
    });
    

    https://jsfiddle.net/dotspencer/6reL64ss/

    【讨论】:

      【解决方案2】:

      在父 div 块之后添加以下代码。

       $(input[type=radio]).change(function(){
           $(this).is(':checked') && $(this).parent().find('button').prop('disabled', false) || $(this).parent().find('button').prop('disabled', true);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        • 2018-06-03
        • 2012-04-02
        相关资源
        最近更新 更多