Get the value from the textbox and output it

How to get value from myTextbox

and output to <p>

?

Why I got the error: [object HTMLInputElement]

<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTextbox");
    document.getElementById("myOutput").innerHTML = x;
}
</script>

      

+3


source to share


6 answers


You will receive this error message because - . This means that it is difficult (the text box is , , etc.) and do not know how / what should be thought of as . The result is it . x

object

value

name

onclick

string

type

[object HTMLInputElement]

To get , you have to access the property . value

object

x.value



function myFunction() {
    var x = document.getElementById("myTextbox");
    document.getElementById("myOutput").innerHTML = x.value;
}
      

<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>
      

Run codeHide result


+3


source


To retrieve data from a control you have to use .value

try it



var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;

      

+1


source


Access the text in the input with .value

:

<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTextbox");
    document.getElementById("myOutput").innerHTML = x.value;
}
</script>
      

Run codeHide result



For fun, you can automatically update <p>

:

<input type="text" id="myTextbox" onchange="myFunction()" onkeyup="this.onchange();">
<p id="myOutput"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTextbox");
    document.getElementById("myOutput").innerHTML = x.value;
}
</script>
      

Run codeHide result


+1


source


You need to extract the value of the textbox and then pass it to the paragraph tag. You have an error because you are trying to insert a text box into a paragraph.

function myFunction() {
    var x = document.getElementById("myTextbox");
    document.getElementById("myOutput").innerHTML = x.value;
}
      

<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>
      

Run codeHide result


0


source


<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>

<script>
    function myFunction() {
        var x = document.querySelector("#myTextbox");
        document.querySelector("#myOutput").innerHTML = x.value;
    }
</script>

      

0


source


You missed the value of the input field, please try fiddle

var x = document.getElementById("myTextbox").value;

      

0


source







All Articles