javascript checkbox checked – Inspect the checked property of the element. Find out how to check the state of a checkbox, looking if it is checked or not, using JavaScript.
javascript checkbox checked
Checking if a checkbox is checked. Check/Uncheck checkbox with JavaScript and jQuery – First of all, select the checkbox using the selecting DOM methods like as getElementById() or querySelector().
Using Javascript:
// Check document.getElementById("is_active").checked = true; // Uncheck document.getElementById("is_active").checked = false;
Using jQuery:
// Check $("#is_active").prop("checked", true); // Uncheck $("#is_active").prop("checked", false);
// Check $("#is_active").attr("checked", true); // Uncheck $("#is_active").attr("checked", false);
Also Read : How To Get All Checked Checkbox Value In Javascript?
javascript checkbox checked Example
Say you have this checkbox:
<input type="checkbox" class="is_active" />
You can see if it’s checked using
document.querySelector('.is_active').checked
You can also check if looking for .is_active:checked does not return null:
document.querySelector('.is_active:checked') !== null
but I think looking for .checked is cleaner.
Note: Do NOT use getAttribute() looking for the checkbox checked attribute value, because that’s always true if the checkbox is checked by default in this methods:
<input type="is_active" checked />
Also don’t check for the value of a checkbox HTML element. this is always on, regardless whether the checkbox is checked or not.
How to get all checked checkbox value in JavaScript?
index.html
<html> <body> <h2 style="color:blue">Create a checkbox and get its value</h2> <h3> Are you a indian Cricketer? </h3> Yes: <input type="checkbox" id="playerTeam1" value="Yes, I'm a indian Cricketer"> No: <input type="checkbox" id="playerTeam2" value="No, I'm not a indian Cricketer"> <br> <br> <button onclick="checkCheckbox()">Submit</button> <br> <h4 style="color:blue" id="output"></h3> <h4 style="color:red" id="error"></h3> <script> function checkCheckbox() { var yes = document.getElementById("playerTeam1"); var no = document.getElementById("playerTeam2"); if (yes.checked == true && no.checked == true){ return document.getElementById("error").innerHTML = "Please mark only one checkbox either Yes or No"; } else if (yes.checked == true){ var y = document.getElementById("playerTeam1").value; return document.getElementById("output").innerHTML = y; } else if (no.checked == true){ var n = document.getElementById("playerTeam2").value; return document.getElementById("output").innerHTML = n; } else { return document.getElementById("error").innerHTML = "*Please mark any of checkbox"; } } </script> </body> </html>
I hope you get an idea about javascript checkbox checked.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.