-4

I have 2 forms in one page and i need to call one function in js when i submit my forms. Can i use 2 onsubmit events in the same page? It not works in my code project. For example:

    <form id="form1" role="form" method="POST" action="script1.php" onsubmit="return validateAccess()">
.....
    </form>

    <form id="form2" role="form" method="POST" action="script2.php" onsubmit="return validateLogin()">
.....
    </form>

1 Answers1

2

Yes you can do this. But, don't use inline HTML event attributes as that is a 20+ year old technique that, while works, has many reasons not to use them.

document.getElementById("form1").addEventListener("submit", validateAccess);
document.getElementById("form2").addEventListener("submit", validateLogin);

function validateAccess(evt){
  evt.preventDefault(); // <-- Only here for demonstration.
  console.log("Form 1 submitted!");
}

function validateLogin(evt){
  evt.preventDefault(); // <-- Only here for demonstration.
  console.log("Form 2 submitted!");
}
<form id="form1" role="form" method="POST" action="script1.php">
  <button type="submit">Submit Form 1</button>
</form>

<form id="form2" role="form" method="POST" action="script2.php">
  <button type="submit">Submit Form 2</button>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Thanks. How can i do if inside a function like validateAccess() there is also an ajax call? How can i "wait" the ajax call execution is finished before submit? – Samuele Bianchi Apr 27 '18 at 11:41
  • @SamueleBianchi Well, that's a very different question, but essentially, you wouldn't use *submit* buttons, you'd have regular buttons and when the button gets clicked, you start the AJAX call. Then, in the AJAX success callback, you'd manually submit the form with the form's `.submit()` method. – Scott Marcus Apr 27 '18 at 12:08