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

Display textbox on button click using JavaScript

To display a textbox on a button click using JavaScript, you can follow the steps below.

  1. Create an HTML button element with an onclick attribute that calls a JavaScript function when clicked.
  2. In the JavaScript function, get a reference to the textbox element using its id.
  3. Set the display style property of the textbox element to "block" to make it visible.
<button onclick="myFunction()">Show Textbox</button>
<input style="display: none;" type="text" id="my-textbox" placeholder="Type your name">
<script>
function myFunction() {
  let textbox = document.getElementById("my-textbox");
  textbox.style.display = "block";
}
</script>

In the above example, we create an HTML button element with an onclick attribute that calls a JavaScript function myFunction when clicked.

In the myFunction() function, we use getElementById() method to get a reference to the textbox element with id "my-textbox". Then, we set its display style property to "block", which makes it visible.

Show and hide textbox on button click using JavaScript #

To show and hide a textbox when a button is clicked using JavaScript, you can use the style.display property to set the visibility of the textbox. Here is the example.

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

When the button is clicked, the myFunction() function is called, which retrieves the textbox element using the getElementById() method, and sets its display style property to either "none" (to hide the textbox) or "block" (to show it), depending on its current value.

save
listen
AI Answer
Write Your Answer
loading
back
View All