Reputation: 15
I am trying to code a program that allows a user to type input and then press a button and the input be printed. I can not seem to get the JavaScript to save the user input. I think it has to do with the value attribute of the text input feild not updating so the JavaScript cannot retrive it. I do not know how to fix this and therfore cannot see if that is what is causing the issue. Any help would be appreciated.
var n = document.getElementById('userInput').value;
function runCode() {
document.getElementById('test').innerHTML = n;
}
<input type="text" id="userInput">
<button type=button id="btn" onclick="runCode()">Click Me!</button>
<p id="test">Orginal Text</p>
Upvotes: 0
Views: 58
Reputation: 68933
Since you are taking the value on page load the value is empty, you should take the value inside the click handler function.
Please Note: If the value is a plain string (not htmlString) instead of innerHTML
it is better to use textContent
or innerText
property of the element.
<input type="text" id="userInput">
<button type=button id="btn" onclick="runCode()">
Click Me!
</button>
<p id="test">
Orginal Text
</p>
<script>
//console.log(document.getElementById('userInput').value == "") // true
function runCode() {
var n = document.getElementById('userInput').value;
document.getElementById('test').textContent = n;
}
</script>
Upvotes: 3
Reputation: 894
You are referencing the value of the input at the start of the JS execution which will have the initial value of the input which is empty string.
Try putting this
var n = document.getElementById('userInput').value;
inside the function
Upvotes: 1