Search code examples
javascripthtmlformsgetelementbyid

Value of form input is blank in JavaScript


When I try to retrieve text that was entered in a form, the result is blank.

document.getElementById("pass").addEventListener("keydown", function() {
  document.getElementById("pass").style.backgroundColor = "#DFFEFE";
});
document.getElementById("pinCode").addEventListener("keydown", function() {
  document.getElementById("pinCode").style.backgroundColor = "#DFFEFE";
});
var pass = document.getElementById("pass").value;
var pinCode = document.getElementById("pinCode").value;

function createCookie() {
  window.alert(pass);
}
<div id="validation">
  <form id="validationForm">
    <fieldset>
      <label for="pass">Password:</label><br />
      <input type="text" id="pass" name="pass" /><br />
      <label for="pinCode">4-digit PIN:</label><br />
      <input type="text" id="pinCode" name="pinCode" /><br />
      <input type="submit" value="Log In" onclick="createCookie()" />
      <p id="rightorwrong"></p>
    </fieldset>
  </form>
</div>
<script type="text/javascript" src="password.js"></script>

When the user enters data in the form and presses submit, the function createCookie() is called. I know this works because if I put in window.alert("test"); in the function, it works. Therefore the problem is in the pass.

I tried removing the value from var pass = document.getElementById("pass").value;, but that didn't work either.

For clarification, this is what shows up when I press submit on the form:enter image description here

I'm stumped, because this is also relatively simple code. (I am on Chrome 84.)

TIA


Solution

  • You must use value inside the function like that:

    document.getElementById("pass").addEventListener("keydown", function() {
        document.getElementById("pass").style.backgroundColor = "#DFFEFE";
    });
    document.getElementById("pinCode").addEventListener("keydown", function() {
        document.getElementById("pinCode").style.backgroundColor = "#DFFEFE";
    });
    
    
    function createCookie() {
       var pass = document.getElementById("pass").value;
       var pinCode = document.getElementById("pinCode").value;
        window.alert(pass); 
          window.alert(pinCode); 
    }
    <div id = "validation">
        <form id = "validationForm">
            <fieldset>
                <label for = "pass">Password:</label><br  />
                <input type = "text" id = "pass" name = "pass"  /><br  />
                <label for = "pinCode">4-digit PIN:</label><br  />
                <input type = "text" id = "pinCode" name = "pinCode"  /><br  />
                <input type = "submit" value="Log In" onclick = "createCookie()"  />
                <p id = "rightorwrong"></p>
            </fieldset>
        </form>
    </div>
    <script type = "text/javascript" src = "password.js"></script>