skip to Main Content

How do I return a variable value (test) in multiple places in my HTML <p> tag.

The variable displays correctly in the first instance but is blank in the second. What am I doing wrong?

var name = document.querySelector("#NameInput").value;

function fillData() {
  document.querySelector("#nameOutput").innerHTML = name;
}
<p>I understand your name is <span><output id="name"></output></span>.</p>
<p>It's nice to meet you `your text`<span><output id="name"></output></span>.</p>

2

Answers


  1. const input = document.querySelector('#name-output');
    input.addEventListener('input', () => 
      document.querySelectorAll('.name-output').forEach(span => span.textContent = input.value)
    );
    <input id="name-output"/>
    <p>I understand your name is <span class="name-output"></span>.</p>
    <p>It's nice to meet you `your text`<span class="name-output"></span>.</p>
    Login or Signup to reply.
  2. Your IDs should be unique. Also, the id "nameOutput" does not exist in your HTML code.

    Here’s a quick solution:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Variable Output Example</title>
    </head>
    <body>
        <h1>Variable Output Example</h1>
    
        <label for="NameInput">Enter your name:</label>
        <input id="NameInput" type="text">
    
        <button onclick="fillData()">Submit</button>
        <p>I understand your name is <span><output id="nameOutput1"></output></span>.</p>
        <p>It's nice to meet you, <span><output id="nameOutput2"></output></span>.</p>
    
        <script>
            function fillData() {
                var name = document.querySelector("#NameInput").value;
                document.querySelector("#nameOutput1").innerHTML = name;
                document.querySelector("#nameOutput2").innerHTML = name;
            }
        </script>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search