In this article I will explain with an example, how to show and hide TextBox on Button Click using JavaScript and jQuery.
When the Yes Button is clicked, the TextBox will be shown and when the No Button is clicked the TextBox will be hidden.
Show Hide TextBox on Button Click using JavaScript
The HTML Markup consists of two HTML Buttons and an HTML DIV consisting of a TextBox.
Both the Buttons have been assigned a JavaScript OnClick event handler.
When any of the Buttons are clicked, the ShowHideDiv JavaScript function is executed inside which based on whether the Yes or No Button is clicked, the TextBox will be shown or hidden respectively using JavaScript.
<script type="text/javascript">
function ShowHideDiv(btnPassport) {
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = btnPassport.value == "Yes" ? "block" : "none";
}
</script>
<span>Do you have Passport?</span>
<input type="button" value="Yes" onclick="ShowHideDiv(this)" />
<input type="button" value="No" onclick="ShowHideDiv(this)" />
<hr />
<div id="dvPassport" style="display: none">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
Show Hide TextBox on Button Click using jQuery
The HTML Markup consists of two HTML Buttons and an HTML DIV consisting of a TextBox.
Both the Buttons have been assigned a jQuery Click event handler.
When any of the Buttons are clicked, based on whether the Yes or No Button is clicked, the TextBox will be shown or hidden respectively using jQuery.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("input[name=btnPassport]").click(function () {
if ($(this).val() == "Yes") {
$("#dvPassport").show();
} else {
$("#dvPassport").hide();
}
});
});
</script>
<span>Do you have Passport?</span>
<input type="button" value="Yes" name = "btnPassport" />
<input type="button" value="No" name = "btnPassport" />
<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