1

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.

1
  • 2
    You need to concatenate strings instead of reassigning it, like .innerHTML += Html Commented Jul 28, 2024 at 11:53

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

Comments

4

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.