0

Hi I am trying to have the event listener below update the variable auth to true if the user enters the right password. However, when I run the file and do the submission the variable auth is not updated.

auth = false;
//For the event listeners
console.log(auth)

console.log("current value of auth variable is: ")
console.log(auth);

// first we need to grabe the value that the user enters
const password = document.getElementById("password")


const ourform = document.getElementById("simplepwform");

ourform.addEventListener('submit', (e) => {

  if (password.value === 'apw') {
    auth = true;
    console.log(auth);
    alert("That's right. Check the value of the auth variable in console.")

  } else {
    alert("Wrong password. Please try again.")
  }

})
<div class="center">
  Form practice
</div>

<div id="simplepwform">
  <form method="GET">
    <input id="password" , name="password">

  </form>

</div>

I tried the above and was expecting that after entering the right password then auth would be updated.

imvain2
  • 15,480
  • 1
  • 16
  • 21
jcgblue
  • 3
  • 2
  • 3
    The problem that you are having is when you rely on the submit event of a form, you will need to stop if from actually submitting the form. You can do this by adding **e.prevenDefault();** as the first line under **ourform.addEventListener** – imvain2 Apr 04 '23 at 20:44
  • I had a typo its supposed to be **e.preventDefault();** – imvain2 Apr 04 '23 at 21:04
  • 1
    Does this answer your question? [Intercept a form submit in JavaScript and prevent normal submission](https://stackoverflow.com/questions/5384712/intercept-a-form-submit-in-javascript-and-prevent-normal-submission) – imvain2 Apr 04 '23 at 21:08
  • Thank you. Those suggestions helped and I actually am going to use localStorage to hold the value. How do I close a question if there isn't an answer? Should I answer it myself? – jcgblue Apr 05 '23 at 05:49
  • It is allowed and totally fine to answer your own question, if it may still be relevant (and better that leaving it unanswered for ever). If an answer to another question is sufficient _(as imvain2 suggested)_, you should close your question as "duplicate", but you need more reputation for that, i believe. – kca Apr 05 '23 at 18:52
  • ... see also: [Can I answer my own question?](https://stackoverflow.com/help/self-answer) – kca Apr 05 '23 at 18:58

0 Answers0