Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 27, 2023 › #HowTo #Input

Show Hide TextBox on Button Click using JavaScript

You can use JavaScript to toggle the display property of the textbox using a function called myFunction(). Here's an example of how to do this with the button text changing based on the current state of the textbox.

<button id="my-button" onclick="myFunction()">Show</button>
<input style="display: none;" type="text" id="my-textbox" placeholder="Type your name">
<script>
function myFunction() {
  let textbox = document.getElementById("my-textbox");
  let button = document.getElementById("my-button");
  if(textbox.style.display === "none") {
    textbox.style.display = "block";
    button.textContent = "Hide";
  } else {
    textbox.style.display = "none";
    button.textContent = "Show";
  }
}
</script>

In the about example, the button initially says "Show" and when clicked it toggles the display property of the textbox between "none" and "block", as well as changing the button text between "Show" and "Hide". The getElementById() method is used to get a reference to the button and textbox elements, and the textContent property is used to set the button text.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

<input type="button" id="toggleButton" value="Hide Textbox"/>
<input type="text" id="myTextbox"/>
	<script>
		$(document.ready(function() {
			$("#toggleButton").click(function() {
				$("#myTextbox").toggle();
				if($("#myTextbox").is(":visible")) {
					$(this).val("Hide Textbox");
				} else {
					$(this).val("Show Textbox");
				}
			});
		});
	</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All