I would like to display the result from the name field in a read-only text field called output. I have it working via .innerHTML
, but I’m not sure how to get the result into a text box.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
<!DOCTYPE html>
<html>
<body style="text-align:center;">
<h1 style="color:green;">
</h1>
<h2>Text value property</h2>
<p>
Change the text of the text field, and then click the button below.
</p>
Name:<input type="text" id="myText" value="Mickey">
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
Output:<input type="text" id="myText" readonly>
</body>
</html>
I would like to get the result inside a read-only text field.
3
Answers
Try the readonly property on the input element that’s going to hold the output :
I was able to get it to work using this code.
All you need to do is set the
.value
property of the output text input. The.value
property can be written to via JavaScript even if it is read only to the user. Also, make sure that your input and output fields don’t share the same ID:It’s also a good practice to use
.addEventListener()
instead ofonclick
handlers. It is the newer way of doing event handlers.