0

I have a simple html form and Javascript. I have been trying to prevent form submission. but it ignores my code e.preventDefault() and continues to submit and refreshes the page anyways.

most solutions I encountered include JQuery. can't this be done without JQuery?
why is this not working? what is the problem?

<html>
  <head>
      <script>
          function onsubmit(e) {
              e.preventDefault();
              e.stopPropagation();

              console.log("submitting...");
              return false;
          }
      </script>
  </head>

  <body>
      <form method="POST" onsubmit="onsubmit">
          <input placeholder="email" style="display:block"> </input>
          <input placeholder="password" style="display:block"> </input>
          <input type="submit" value="login" style="display:block"> </input>
      </form>
  </body>
</html>
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
Abraham
  • 12,140
  • 4
  • 56
  • 92
  • The inline listener doesn't do anything, your submit handler is never called. – Teemu Feb 24 '21 at 13:28
  • @Teemu why is that? can I make it work? – Abraham Feb 24 '21 at 13:30
  • [Drop the inline listener](https://stackoverflow.com/a/63119431/1169519), it causes you a ton of problems already. – Teemu Feb 24 '21 at 13:31
  • @Teemu, I don't get the reason, but it worked when I used `addEventListener` instead, Thank you – Abraham Feb 24 '21 at 13:48
  • The reason is explained in the Often misunderstood behavior chapter, the actual listener is the code in the attribute itself, your only code is a reference to a function. A plain reference does nothing, and even calling the function wouldn't fix the problem, because as explained in #1 in Differences in the execution chapter, `onsubmit` refers to `onsubmit` property of the form, which is never defined in your code. After fixing all this, the event object is still not passed to your function, and `e` would be `undefined`. Simply don't use inline listeners, it's too much troubles. – Teemu Feb 24 '21 at 14:05

1 Answers1

0

Though I don't know the reason why the inline event listener didn't work, as @teemu suggested in the comment, It worked for me when I discarded the inline onsubmit event listener and rather used addEventListener.

document.addEventListener("DOMContentLoaded", (e)=>{
    document.querySelector("form").addEventListener("submit", onsubmit);
}

added this in of the <script>, and it worked

Abraham
  • 12,140
  • 4
  • 56
  • 92