In this article I will explain with an example, how to implement OnClick event of HTML CheckBox using JavaScript.
For illustration purposes, when the CheckBox is clicked based on whether it is checked (selected) or unchecked (unselected), a JavaScript function will be called within which the HTML DIV with TextBox will be shown or hidden.
CheckBox OnClick event example in JavaScript
The HTML Markup consists of a CheckBox and an HTML DIV consisting of a TextBox. The CheckBox has been assigned a JavaScript OnClick event handler.
When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.
<script type="text/javascript">
function ShowHideDiv(chkPassport) {
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = chkPassport.checked ? "block" : "none";
}
</script>
<label for="chkPassport">
<input type="checkbox" id="chkPassport" onclick="ShowHideDiv(this)" />
Do you have Passport?
</label>
<hr />
<div id="dvPassport" style="display: none">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
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
Download Code