In this article I will explain with an example, how to check whether a CheckBox is checked (selected) or not selected (unchecked) using JavaScript and jQuery.
Check whether a CheckBox is checked (selected) or not using JavaScript
The following HTML Markup consists of an HTML CheckBox and a Button. When the Button is clicked, the Check JavaScript function gets executed which first references the CheckBox using its ID and then based on whether it is checked or unchecked, displays a JavaScript alert message box.
<label for="chkPassport">
<input type="checkbox" id="chkPassport" />
Do you have Passport?</label>
<br />
<br />
<input type="button" id="btnCheck" value = "Check" onclick = "Check()" />
<script type="text/javascript">
function Check() {
var chkPassport = document.getElementById("chkPassport");
if (chkPassport.checked) {
alert("CheckBox checked.");
} else {
alert("CheckBox not checked.");
}
}
</script>
Check whether a CheckBox is checked (selected) or not using jQuery
The following HTML Markup consists of an HTML CheckBox and a Button. When the Button is clicked, a jQuery click event handler is executed which first references the CheckBox using its ID and then based on whether it is checked or unchecked, displays a JavaScript alert message box.
<label for="chkPassport">
<input type="checkbox" id="chkPassport" />
Do you have Passport?</label>
<br />
<br />
<input type="button" id="btnCheck" value = "Check" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCheck").click(function () {
var isChecked = $("#chkPassport").is(":checked");
if (isChecked) {
alert("CheckBox checked.");
} else {
alert("CheckBox not checked.");
}
});
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads