skip to Main Content

Here is the code I have at the moment…

<button id="a" onclick="c()"></button>

<div id="b"></div>
function c()
{
    var Html = '<input type="text" id="a">';
    document.getElementById('b').innerHTML = Html;
}

The problem is that, when the button is clicked several times, it only adds one textbox. I need it to add a textbox on every click.

2

Answers


  1. Use insertAdjacentHTML() to append HTML to an element (never do .innerHTML += html, since it destroys previously added elements (a lot of bugs because of that reported on Stackoverflow as questions)).

    https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

    function c()
    {
        var Html = '<input type="text" id="a">';
        document.getElementById('b').insertAdjacentHTML('beforeend', Html);
    }
    <button id="a" onclick="c()">Append</button>
    
    <div id="b"></div>
    Login or Signup to reply.
  2. You can create the element first with parameters and append it to your DOM.
    I recommend you to use descriptive function names and also for IDs or random IDs longer than a char. You can see an example below for creating random IDs.

    function addInput() {
      let input = document.createElement("input");
      input.type = "text";
      input.name = "input";
      input.id = createId();
      input.className = "input";
      input.placeholder = "Enter your name";
      document.getElementById("container").appendChild(input);
    }
    
    function createId() {
      return Math.random().toString(36).substr(2, 9);
    }
    #container {
        display: flex;
        flex-direction: column;
    }
    
    .input {
        margin-bottom: 4px;
        width: 20vw;
    }
    
    #add {
        margin-bottom: 4px;
    }
    <button id="add" onclick="addInput()">Add input to container</button>
    
    <div id="container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search