thatcomputerguy
thatcomputerguy

Reputation: 1

sending user input to div

Hello I am here with a quick question on sending user input to a div section of an html document. I asked this question earlier and it seemed to be too broad so I'm going to try to be more specific this time.

I am attempting to send a user input to the div onclick of the send button but every time the code is simply changing the text rather than printing the next text under it. I'm curious what I'm doing wrong with this. Thanks for reading and here's my code.

<div id="out"</div>
<input type="text" name="textIn" id="txtin">
<input type="button" value="Hit me" onclick="hello()"></input>
<script>
 function hello() {
    document.getElementById("out").innerHTML = 
    document.getElementById('txtin').value + "<br />"
}
</script>

https://jsfiddle.net/su0o83hj/1/

Upvotes: 0

Views: 50

Answers (3)

Yosvel Quintero
Yosvel Quintero

Reputation: 19090

You can use Element.insertAdjacentHTML() passing the first parameter beforeend:

var out = document.getElementById('out'),
    txtin = document.getElementById('txtin');
    
function hello() {
  out.insertAdjacentHTML('beforeend', txtin.value + '<br>');
}
<div id="out"></div>
<input type="text" name="textIn" id="txtin">
<input type="button" value="Hit me" onclick="hello()">

Upvotes: 0

dloeda
dloeda

Reputation: 1548

You have some syntax errors, fix it and it will works

<div id="out"></div>
<input type="text" name="textIn" id="txtin" />
<input type="button" value="Hit me" onclick="hello()" />
<script>
 function hello() {
    document.getElementById("out").innerHTML += 
    document.getElementById('txtin').value + "<br />"
}
</script>

Upvotes: 0

Jay Buckman
Jay Buckman

Reputation: 578

If you want to append to the existing text, use += instead of = in the function:

function hello() {
    document.getElementById("out").innerHTML += 
    document.getElementById('txtin').value + "<br />"
}

Upvotes: 1

Related Questions