切换两个复选框

Toggle two checkboxes

我有两个复选框,每个复选框分别处理垂直和水平状态。两个都关没问题,但是如果一个开另一个必须关,最重要的是不能两个都开。

我不想jQuery这里。

如果我两个都未选中,我点击水平,然后点击垂直,它们将切换,因为水平未选中,垂直将变为选中。

但如果我从垂直方向开始,我就无法检查水平方向。

完整代码在 github and demo running on gh-pages

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Toggle</title>
</head>
<style>
  .constraint {
    color: #007bff;
    padding: 0rem .5rem;
  }
  
  span.horz:before {
    content: "94";
  }
  
  span.vert:before {
    content: "95";
  }
</style>

<body>
  <span class="constraint">Constraint: </span>
  <span class="constraint vert">
        <input type="checkbox" id="vertical" onchange="constraints()">
        <span class="constraint horz"></span>
  <input type="checkbox" id="horizontal" onchange="constraints()">
</body>
<script type="text/javascript">
  function constraints() {
    inputVert = document.getElementById("vertical");
    inputHorz = document.getElementById("horizontal");
    console.log("initially: vert:" + inputVert.checked);
    console.log("initially: horz:" + inputHorz.checked);
    if (inputVert.checked) {
      console.log("vert clicked -> vert:" + inputVert.checked);
      console.log("vert clicked -> horz:" + inputHorz.checked);
      // inputHorz = document.getElementById("horizontal");
      inputHorz.checked = false;
      // inputVert.checked = true;
    };
    if (inputHorz.checked) {
      console.log("horz clicked -> vert:" + inputVert.checked);
      console.log("horz clicked -> horz:" + inputHorz.checked);
      // inputVert = document.getElementById("vertical");
      inputVert.checked = false;
      // inputHorz.checked = true;
    };
  }
</script>

</html>

非常感谢任何帮助,

谢谢

这是使用输入收音机的经典场景。这迫使用户最多选择一个选项。 https://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio

有了JQuery你可以这样做,希望这对你有帮助

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

<head>
  <meta charset="utf-8">
  <title>Toggle</title>
</head>
<style>
  .constraint {
    color: #007bff;
    padding: 0rem .5rem;
  }

  span.horz:before {
    content: "94";
  }

  span.vert:before {
    content: "95";
  }
</style>

<body>
  <span class="constraint">Constraint: </span>
  <span class="constraint vert">
  <input type="checkbox" id="vertical">
  <span class="constraint horz"></span>
  <input type="checkbox" id="horizontal">
</body>
<script type="text/javascript">
  
    $('#vertical').change(function() {
        if($(this).is(":checked")){
          $('#horizontal').attr('checked', false);
        }    
    });
    
    $('#horizontal').change(function() {
        if($(this).is(":checked")){
          $('#vertical').attr('checked', false);
        }    
    });
  
  
</script>

</html>

的基础上,可以进一步简化为:

$('#vertical').on("change", function() {
   $('#horizontal').attr('checked', !$(this).is(":checked"));
});
    
$('#horizontal').on("change", function() {
   $('#vertical').attr('checked', !$(this).is(":checked"));
});