【问题标题】:Reaction to radio button status with jQuery使用 jQuery 对单选按钮状态的反应
【发布时间】:2021-09-27 14:57:04
【问题描述】:

我是 JS 和 jQuery 的新手,我现在只想用它实现一个功能。所以我的问题可能看起来很幼稚。

我的 HTML 表单有几行和两列:左和右。左列包含与右列相同的所有单选按钮选择。我想让这个单选按钮表单以这样的方式工作,如果在左栏中做出特定选择,则相同的选择在右栏中必须变为不可用(灰色),反之亦然。

下面的 JS/jQuery 脚本应该可以做到这一点,但是当取消选择某个单选按钮时如何撤消相关操作?是否有必要获取一列中的所有表单元素并检查每个元素是否需要不灰显,或者是否有更简单的方法?

function toggleRadio() {
      left = $("input[type='radio'][class='left_column']:checked");
      left_val = left.val();
      right = $("input[value=" + left_val + "][class='right_column']");
      left.change(function() {
        right.attr('disabled', true);
      }).change();
}

【问题讨论】:

    标签: javascript jquery forms radio-button


    【解决方案1】:

    我不能说我完全理解你想要做什么。但我希望这个例子对你有用。

    HTML

    <div class="row">
      <div class="col">
    
        <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group1" value="rad1" checked>
            Option 1
          </label>
        </div>
        
        <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group1" value="rad2">
            Option 2
          </label>
        </div>
        
        <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group1" value="rad3">
            Option 3
          </label>
        </div>
    
      </div>
      <div class="col">
      
         <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group2" value="rad1" checked disabled>
            Option 1
          </label>
        </div>
        
        <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group2" value="rad2">
            Option 2
          </label>
        </div>
        
        <div class="form-check">
          <label>
            <input class="form-check-input" type="radio" name="group2" value="rad3">
            Option 3
          </label>
        </div>
      
      </div>
    </div>
    

    JS (jQuery)

    $(document).ready(function(){
    
        $("input[type='radio']").change(function(){
      
            var name  = $(this).prop("name"),
              val   = $(this).val(),
              target = (name === "group1") ? 'group2' : 'group1';
              
        $("input[type='radio']").prop("disabled", false);
    
    
        $("input[name='" + target + "'][value='" + val + "']")
            .prop("checked", true)
            .prop("disabled", true);
      
      });
    
    
    }); //doc ready end
    

    演示 https://jsfiddle.net/caneroncel/3vmstpjf/20/

    【讨论】:

    • 谢谢,这正是我想要的,除了我必须删除 .prop("checked", true) 部分。
    • 我把它改成了.prop("checked", false)。再次感谢。
    猜你喜欢
    • 2019-06-12
    • 2011-04-28
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多