Home > Software engineering >  Why is the value of my password field always an empty string?
Why is the value of my password field always an empty string?

Time:04-28

I've been working on my javascript skills lately and the password validation has given me a lot of trouble. The last thing that is stopping me is that the password field always has a value of an empty string for some reason.

It always logs out an empty string, no matter what i put in the input field. I've tried a different browser but that did not have an effect.

<input type="password" id="password">
<button type="submit" onclick="submitIt()">
Submit
</button>

js

const passWord = document.getElementById('password').value

function submitIt() {
console.log(passWord)
}

Here is the jsfiddle: https://jsfiddle.net/k4owfLzn/3/

CodePudding user response:

Your value is always empty because the value of passWord is set on the loading of page. It is not updated after a user types in a value.

If you modify the code so it is like this you should get the value.

function submitIt() {
  const passWord = document.getElementById('password').value;

  console.log('passWord: ', passWord)
}
  • Related