javascript
Check whether a checkbox is checked or not using Javascript only
You can use the .checked property of the input element using javascript to check whether a checkbox is checked or not.
var checkbox = document.getElementById("checkbox_id");
if (checkbox.checked) {
console.log("Checkbox is checked");
} else {
console.log("Checkbox is not checked");
}
In the code snippet, we have a checkbox which has id checkbox_id. We are getting this checkbox using document.getElementById("checkbox_id").
We are checking using the .checked property to check if the checkbox is checked.
You can check the full code below.
<input type="checkbox" id="checkbox_id" checked>
<div id="status"></div>
<script>
var checkbox = document.getElementById("checkbox_id");
checkbox.addEventListener('change', function() {
document.getElementById("status").innerHTML = checkbox.checked
});
</script>
Live Demo
var checkbox = document.getElementById("checkbox_id");
checkbox.addEventListener('change', function() {
if (checkbox.checked) {
// -> Checkbox is checked
} else {
// -> Checkbox is not checked
}
});
In the code, we are checking the checkbox checking status when we are clicking on it and it is selecting or un-selecting.
var checkbox = document.getElementById("checkbox_id");
checkbox.addEventListener('change', function() {
if (checkbox.checked) {
alert("Checkbox is selected");
}
});
In the above code, we are showing an alert when the checkbox is selected.
Was this helpful?
Similar Posts
- Check if a string is Palindrome or not using Javascript
- Check if video is stopped or playing Javascript only
- Load or preview html to Iframe using Javascript only
- How to make HTTP requests using Javascript Only
- Get all values from an array which does not exist in other array Lodash
- Enter only number field validation redux form
- Methods to check empty array using javascript