且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JQUERY立即将选定的复选框值从一个复选框复制到另一个复选框

更新时间:2023-01-07 08:36:56

我相信我知道您要做什么.看来使用类可能更容易(按类名称对复选框进行分组)

I believe I know what you are trying to do. This seems like it could be easier with classes (group the checkboxes by class names)

当单击具有checkboxA类的复选框时,还将检查具有checkboxB类的复选框,并且前提是它也具有与checkboxA相同的值

When a checkbox with checkboxA class is clicked it will also check the checkbox with class checkboxB and only if it also has the same value as checkboxA

$(document).ready(function() {
  $(".checkboxA").change(function() {
    let selectedValA = $(this).val();
    let isAChecked = $(this).prop("checked");
    // get a checkbox from the checkboxs with class "checkboxB" and have the same value as the checked checkboxA and set its checked prop to the same as checkboxA
    $(`.checkboxB[value=${selectedValA}]`).prop("checked", isAChecked);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- checkbox set A -->
<div>
one <input type="checkbox" class="checkboxA" value="1"/>
two <input type="checkbox" class="checkboxA" value="2"/>
three <input type="checkbox" class="checkboxA" value="3"/>
four <input type="checkbox" class="checkboxA" value="4"/>
five <input type="checkbox" class="checkboxA" value="5"/>
</div>

<br/>
<br/>

<!-- checkbox set B -->
<div>
one <input type="checkbox" class="checkboxB" value="1"/>
two <input type="checkbox" class="checkboxB" value="2"/>
three <input type="checkbox" class="checkboxB" value="3"/>
four <input type="checkbox" class="checkboxB" value="4"/>
five <input type="checkbox" class="checkboxB" value="5"/>
</div>