How to display text input after submitting button in HTML and Javascript

Advertisements

I have an input box that I am typing into and a submit button. I want to display whatever is typed into the input box in a blank pre-existing <p> tag. How can I do this?

I currently have this code:

<label for="moveData">Enter data</label>
<input type="text" id="moveData" name="moveData"><br>
<button id="btn" type="button">Move the data</button>
<script>
    document.getElementById("btn").onclick = function()
    {
    var input = document.getElementById("btn").value;
    document.getElementById("p1").innerHTML = input;
    }
</script>
<p id="p1"></p>

I want the <p id="p1"></p> to be replaced with the user text input as so: <p id="p1">(USER INPUT GOES HERE)</p> after the submit button is clicked.

>Solution :

You are picking the value from the button instead of the input. You just need to change this line:

<label for="moveData">Enter data</label>
<input type="text" id="moveData" name="moveData"><br>
<button id="btn" type="button">Move the data</button>

<script>
    document.getElementById("btn").onclick = function() {
        var input = document.getElementById("moveData").value; // <-- this line
        document.getElementById("p1").innerHTML = input;
    }
</script>

<p id="p1"></p>

Leave a ReplyCancel reply