jeudi 14 septembre 2017

Toggle two checkboxes

I have two checkboxes, each handling a vertical and horizontal state respectively. It is ok if both are off, but if one is on the other must be off and most importantly both can not be on.

I do not want to jQuery here.

If I both are unchecked and I hit the horizontal one and then the vertical, they will toggle, as the horizontal goes unchecked and the vertical will become checked.

But if I do it the other way starting with the vertical, I can't check the horizontal.

<!DOCTYPE html>
<html>

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

  span.horz:before {
    content: "\2194";
  }

  span.vert:before {
    content: "\2195";
  }
</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>

Any help greatly appreciated,

Thanks

Aucun commentaire:

Enregistrer un commentaire