Home > OS >  how to keep the checkbox checked using javascript
how to keep the checkbox checked using javascript

Time:12-20

function check() {
  if (document.getElementById("myCheck").checked == true) {
    document.getElementById("myCheck").checked = true;
  }
}
<!DOCTYPE html>
<html>

<body>
  Checkbox: <input type="checkbox" id="myCheck" onclick="check()">
</body>

</html>

Description

  1. Here I have been trying to keep the check box checked if the check box is already checked.
  2. I tried to check with the status of the check box that if the checkbox is checked then setting the checked as 'true'.
  3. But it keeps unchecking the checkbox if the checkbox is checked.

What do I need

  1. I need to keep the checkbox checked if it's already checked, Please suggest only javascript.

CodePudding user response:

You can remove the condition if (document.getElementById("myCheck").checked == true) if you want to keep it checked once it has been checked for the first time.

function check() {
    document.getElementById("myCheck").checked = true;
}
<!DOCTYPE html>
<html>

<body>
  Checkbox: <input type="checkbox" id="myCheck" onclick="check()">
</body>

</html>

CodePudding user response:

Disable the checkbox after it has been clicked once.

document.getElementById("myCheck").disabled = true;

CodePudding user response:

with inputs we use onchange

const checkbox = document.getElementById('my-checkbox')
checkbox.checked = true
checkbox.onchange = function() {
    checkbox.checked = true
}

CodePudding user response:

You can track if your checkbox is checked by change event listener and make it keep checked if the checkbox is changed (that means if it is checked).

const checkBox = document.querySelector("[type='checkbox']")

checkBox.addEventListener("change", () => {
    checkBox.checked = true
})
  Checkbox: <input type="checkbox" id="myCheck" />

  • Related