Search code examples
javascriptinputvar

How to make user input stored as JavaScript Variable for later use


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>


Solution

  • 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>