I have the following code. How do I let the user keep reusing the input field so they can enter different names, and the text in the textarea will always change to whatever is being entered in the field?
function saveName() {
for (let i = 1; i < 3; i++) {
var name = document.getElementById('name').value;
var snippet = document.getElementById('text'+i).value;
const result = snippet.replaceAll(/name/gi, name);
document.getElementById('text'+i).innerHTML = result;
}
}
<div class="input">
<input class="name" type="text" id="name" maxlength="100" value="" placeholder="Enter name"><br>
<button class="save" id="saveName" onclick="saveName();">Save</button>
</div>
<textarea class="box" id="text1">Hello name</textarea>
<button class="btn1" style="vertical-align:top;">Copy</button>
<textarea class="box" id="text2">Welcome name</textarea>
<button class="btn2" style="vertical-align:top;">Copy</button>
2
Answers
You are replacing the string ‘name’ with the value of the input.
This works the first time, as the text in the
<textarea>
contains the word ‘name’.The second time, however, the text will most likely be something like ‘Hello John’.
My suggestion would be to replace to complete value of the
<textarea>
.First, I would select the textareas with querySelectorAll, so you can get an array of all of them. That way it will handle them dynamically, regardless of how many you have. Then replace the full textContent with Hello + name.