'How to uncheck a checkbox in pure JavaScript?
Here is the HTML Code:
<div class="text">
<input value="true" type="checkbox" checked="" name="copyNewAddrToBilling"><label>
I want to change the value to false. Or just uncheck the checkbox. I'd like to do this in pure JavaScript, without the use of external libraries (no jQuery etc)
Solution 1:[1]
<html>
<body>
<input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
</body>
<script language="javascript">
document.getElementById("check1").checked = true;
document.getElementById("check1").checked = false;
</script>
</html>
I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.
If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.
Solution 2:[2]
Recommended, without jQuery:
Give your <input> an ID and refer to that. Also, remove the checked="" part of the <input> tag if you want the checkbox to start out unticked. Then it's:
document.getElementById("my-checkbox").checked = true;
Pure JavaScript, with no Element ID (#1):
var inputs = document.getElementsByTagName('input');
for(var i = 0; i<inputs.length; i++){
if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){
inputs[i].checked = true;
break;
}
}
Pure Javascript, with no Element ID (#2):
document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;
document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;
Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.
If the element may be missing, you should test for its existence, e.g.:
var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }
With jQuery:
$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);
Solution 3:[3]
There is another way to do this:
//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck
Solution 4:[4]
You will need to assign an ID to the checkbox:
<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">
and then in JavaScript:
document.getElementById("checkboxId").checked = false;
Solution 5:[5]
<html>
<body>
<input id="mycheck" type="checkbox">
</body>
<script>
var check = document.getElementById("mycheck");
check.checked = false;
</script>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gras Double |
| Solution 3 | Yang You |
| Solution 4 | Gary |
| Solution 5 | Cooper |
