Reputation: 97
I would like to display a block of text ("pre" tag), allow a user to type in a textbox, click a button and the text which they typed appears in the block of text.
For example, the block of text will say: "Hello USERNAME, welcome!"
I type: "seba1685", click the button to display: "Hello seba1685, welcome!"
Here is what I have so far:
<input type="text" id="myText" value="USERNAME">
<p>Enter your username above</p>
<button onclick="myFunction()">Try it</button>
<br>
<pre style="color: #000; background: #cccccc; padding:10px; display: inline-flex" id="demo">Hello USERNAME, welcome!</pre>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
But instead of adding text to the block, it REPLACES the entire block. I don't know how to use a variable within this block.
Any ideas would be greatly appreciated - thank you!
Upvotes: 0
Views: 887
Reputation: 780724
Put a span inside the pre block, and update that rather than the whole pre block.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("username").innerHTML = x;
}
<input type="text" id="myText" placeholder="USERNAME">
<p>Enter your username above</p>
<button onclick="myFunction()">Try it</button>
<br>
<pre style="color: #000; background: #cccccc; padding:10px; display: inline-flex" id="demo">Hello <span id="username">USERNAME</span>, welcome!</pre>
Upvotes: 3