将两个复选框绑定在一起

时间:2015-12-27 08:59:38

标签: javascript jquery html checkbox

我有两个复选框

<input class="checkbox1" type="checkbox" name='1' id="example1" value="example1"/> 

<input class="checkbox2" type="checkbox" name='2' id="example2" value="example2"/>

是否可以连接这两个复选框,以便一个复选框的'checked'属性发生的任何事情也会发生在另一个复选框上?它需要为

工作
  1. 用户更改已检查状态

  2. 某些javascript函数会更改已检查状态

  3. 我的实际例子非常复杂,并且有很多复选框。所以我正在寻找一个解决方案,我可以确定两个复选框之间的连接,而不必再考虑它。 谢谢 卡尔

3 个答案:

答案 0 :(得分:6)

当然可以,但为什么如果它们的行为相同,你会有两个复选框?也许一个复选框会更方便。 :)

嗯,无论如何,使用一块jQuery,这应该可以正常工作。此代码段允许您为复选框指定一个组,因此它会自动选择同一组中的其他组。

当然,您可以轻松地将其更改为ID列表,例如,因此行为不需要两种方式,但我无法从您的问题中完全推断出您需要什么。无论如何,添加额外的复选框只需要它们具有正确的属性。

因为它以这种方式使用 FileWriter fw=new FileWriter("C:\\file.json",true); fw.write("ssssss"); fw.close(); 函数,所以它甚至可以用于动态添加的复选框。

on
$(document).on('click', 'input[type="checkbox"][data-group]', function(event) {
  // The checkbox that was clicked
  var actor = $(this);
  // The status of that checkbox
  var checked = actor.prop('checked');
  // The group that checkbox is in
  var group = actor.data('group');
  // All checkboxes of that group
  var checkboxes = $('input[type="checkbox"][data-group="' + group + '"]');
  // All checkboxes excluding the one that was clicked
  var otherCheckboxes = checkboxes.not(actor);
  // Check those checkboxes
  otherCheckboxes.prop('checked', checked);
});

答案 1 :(得分:3)

您可以在复选框上绑定更改事件处理程序,并根据更改的复选框的值,设置其他复选框的值。

$(function() {

  $(".checkbox_class").change(function() {

    var x = this.checked;
    $(".checkbox_class").prop("checked", x);


  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="checkbox1 checkbox_class" type="checkbox" name='1' id="example1" value="example1" />

<input class="checkbox2 checkbox_class" type="checkbox" name='2' id="example2" value="example2" />

答案 2 :(得分:2)

可以绑定以更改或点击事件

&#13;
&#13;
public class Terrain {
    private static int width;
    private static int height;
    private final Map<Location, Person> personAtLocation = new HashMap<>();

    public void addPerson(Person p, Location x){
        personAtLocation.put(x, p);
    }
    ...
}
&#13;
$("#example1").click(function (){
    $("#example2").click();
});

$("#example2").click(function (){
    $("#example1").click();
});
&#13;
&#13;
&#13;