How to Add an input Field on Button Click in JavaScript?

You can use the createElement() and the appendChild() method of JavaScript to add an input field on a button click. This can be done in the following three steps:

  1. Get the parent element using any DOM method such as getElementById() under which you want to add the input field.
  2. Create a new input element using the createElement() method.
  3. Append the newly created input element to the parent element using the appendChild() method.

Here is the full JavaScript code with a live example:

Example:

const container = document.getElementById('input-cont');

// Call addInput() function on button click
function addInput(){
    let input = document.createElement('input');
    input.placeholder = 'Type something';
    container.appendChild(input);
}

The above approach allows the user to add as many input fields as he wants. However, in actual scenarios, it shouldn’t happen.

To keep track of how many input fields has the user already added, you can create a count variable and increment it every time the user adds a new field. If it reaches the max allowed input fields, you can prompt that the max limit is reached.

Here is the updated JavaScript code:

Example:

const container = document.getElementById('input-cont');
var maxInputAllowed = 5;
var inputCount = 0;

// Call addInput() function on button click
function addInput(){
    inputCount++; // Increment input count by one
    if(inputCount>5){
        alert('You can add maximum 5 input fields.');
        return;
    }
    let input = document.createElement('input');
    input.placeholder = 'Type something';
    container.appendChild(input);   
}

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.