Home > Back-end >  Make checkbox functional with Enter key
Make checkbox functional with Enter key

Time:05-31

I'm trying to make the checkbox behave with the Enter key (when tabbed into) the same way it usually does with the space bar or when clicked. I cooked up a case where the checkbox is indeed being checked, but it then doesn't act like it should, i.e. I want it to display a previously hidden text and disappear itself. How can I achieve this? Adding something like document.getElementById("myCheck").click() doesn't work, though.

document.addEventListener('keydown', (e) => {
    if( e.key === "Enter" && e.target.classList.contains('myCheck')){
        e.target.checked = !e.target.checked;
    }
})

function myFunction() {
  var form = document.getElementById("form");
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked === true){
    form.style.display = "none";
    text.style.display = "block";
  } else {
    form.style.display = "inline-block";
    text.style.display = "none";
  }
}
* {
  margin: 10px;
  padding: 0;
  font-size: 50px;
}

input {
  width: 30px;
  height: 30px;
}

p {
  color: red;
  text-transform: uppercase;
}
<form  id="form" style="display:inline-block">
<input type="checkbox"  id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label> 
</form>

<p id="text" style="display: none;">checkbox is checked</p>

CodePudding user response:

All you need to do is trigger the click event, that will check the box. If you manually set checked and then trigger click it will undo the manual setting.

document.addEventListener('keydown', (e) => {
    if( e.key === "Enter" && e.target.classList.contains('myCheck')){
        //e.target.checked = !e.target.checked;
        e.target.click()
    }
})

function myFunction() {
  var form = document.getElementById("form");
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked === true){
    form.style.display = "none";
    text.style.display = "block";
  } else {
    form.style.display = "inline-block";
    text.style.display = "none";
  }
}
* {
  margin: 10px;
  padding: 0;
  font-size: 50px;
}

input {
  width: 30px;
  height: 30px;
}

p {
  color: red;
  text-transform: uppercase;
}
<form  id="form" style="display:inline-block">
<input type="checkbox"  id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label> 
</form>

<p id="text" style="display: none;">checkbox is checked</p>

  • Related