skip to Main Content

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


  1. const result = snippet.replaceAll(/name/gi, name);
    

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

    function saveName() {
      for (let i = 1; i < 3; i++) {
        const name = document.getElementById('name').value;
        document.getElementById('text'+i).textContent = 'Hello ' + name;
      }
    }
    
    Login or Signup to reply.
  2. 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.

    function saveName() {
        let name = document.getElementById('name').value;
        for (inputField of document.querySelectorAll('textarea.box')) {
            inputField.innerText = inputField.textContent = `Hello ${name}`;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search