0

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>

1
  • You are right about the not updating part. You are currently reading the input value once when the page loads. Of course at the time the user didn’t have a chance to input anything yet. Simply reading the input value inside the runCode function will fix this problem. Commented Dec 14, 2019 at 7:00

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.