Blind Roach
Blind Roach

Reputation: 90

Javascript - Display input inside div

So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:

<input type='text' placeholder='Form Name...' id='formNameInput' required>

Into this Div:

<div id="code_output"></div>

I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:

document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;

Why doesn't it show? Does my code need something to trigger the Javascript?

Upvotes: 0

Views: 939

Answers (4)

connexo
connexo

Reputation: 56823

You need to attach an event listener to your input that executes a function any time an input event occurs on the field:

formNameInput.addEventListener('input', function(e) {
  code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>

Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.

If the concept of events is new to you, this might be a good place to get started:

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Upvotes: 0

Surya
Surya

Reputation: 171

function change() {
  document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}

document.getElementById('formNameInput').onkeyup = change

maybe this is what you are trying?

Upvotes: 0

callback
callback

Reputation: 4122

You need to do that whenever the value of formNameInput changes. For that you need an event.

Your code should look like:

document.getElementById("formNameInput").addEventListener('input', function () {
   document.getElementById("code_output").innerHTML += this.value;
});

Upvotes: 0

Tom O.
Tom O.

Reputation: 5941

You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:

document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);

function copyToDiv() {
  document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>

<div id="code_output"></div>

Upvotes: 2

Related Questions