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

Adding textbox on button click with JavaScript

Today we're going to learn how to add a textbox on button click with JavaScript. This is a great way to create forms that are dynamic and interactive for your users.

Adding Textbox on Button Click with JavaScript.#

Let's get started by setting up the HTML form first. We'll need an input field for the user's name, as well as a button labeled "Add Last Name". Here is our basic markup:

<form name="myForm" onsubmit="return validateForm()">  
  Name : <input type="text" id="first-name"> 
  <input type="button" id="last-name" value="Add Last Name"> 
</form> 

Next, let's use some simple JavaScript code to add an additional text box when the user clicks the "Add Last Name" button.

<script>
  document.getElementById("last-name").onclick = function(){   
    let lastName = document.createElement("INPUT");    
    lastName.setAttribute("type", "text");    
    document.getElementsByTagName('form')[0].appendChild(lastName); 
  }; 
</script>

Now if you test this out in your browser you should see that clicking "Add Last Name" will generate another text box below it.

  1. In the above example, the form contains an input field with the id first-name for entering the first name. There is also an input button with the id last-name.
  2. The code attaches an onclick event handler to the last-name button using the document.getElementById() method. When the last-name button is clicked, the event handler function is triggered.
  3. Inside the event handler function, a new HTML input element of type text is created using the document.createElement() method.
  4. The newly created input element is assigned to the variable lastName. The type attribute of the lastName input element is set to text using the setAttribute() method.
  5. The input element is appended as a child to the form element using document.getElementById('my-form').appendChild(lastName).
  6. When the Add Last Name button is clicked, a new text input field will be dynamically added to the form, allowing the user to enter their last name.
save
listen
AI Answer
Write Your Answer
loading
back
View All