javascripthtmltextbox

How can I add a new textbox on every click of a button, in javascript?


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.


Solution

  • 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>