0

I am having a situation where I am not able to figure out who is calling the form submit.

I have a dom like below.

<form method="POST" action="action.do">
<button onclick = "eventHandler()">Test</button>
</form>

Whenever I click on the button I see a breakpoint hit on submit and not able to figure out anything from call stack.

Need help

Raviteja Avvari
  • 252
  • 4
  • 14

3 Answers3

3

In general, avoid using onxyz-attribute-style event handlers. But if you do, call them setting this correctly and passing in the event; you may also want to include return if you want to use return false in the handler to prevent the default action of the event:

<button onclick = "return eventHandler.call(this, event)">Test</button>
<!-- --------------^^^^^^--------------^^^^^^^^^^^^^^^^^             -->

(Without the return, on modern browsers, you can use the preventDefault() method on the event object instead of returning false.)

Within the handler, this will refer to the element (the button, in this case) and the first argument will be the event object, which has other useful information.

Note that this handler does not handle the submit event. It handles a click event on a submit button. submit is an event fired at forms, not buttons.

But, in general I'd recommend modern event handling, which hooks up the event once the button exists:

var btn = document.querySelector("selector-for-the-button");
btn.addEventListener("click", eventHandler, false);

With that, eventHandler will be called with the correct this and passed the event object.

Note: The obsolete browsers IE8 and earlier do not have addEventListener. The obsolete browsers IE9-IE10 have it but pretend they don't when they're in "compatibility" mode. IE11 similarly hobbles itself when in "compatibility" mode. If you need to support any of those, you can use the hookEvent function in this answer.

Or of course, use a library like jQuery, or a framework like AngularJS or React, etc., that handles those cross-browser issues for you.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Because type attribute is not specified in button tag:

<button onclick = "eventHandler()">Test</button>

it takes default type as submit, so on click of this button, submits the form after finishing eventHandler() code. To make button not to submit form, add type attribute with value as button.

Ankush G
  • 989
  • 9
  • 14
0

Below is a complete code for what are you looking for:

function eventHandler(e){
  console.log(e.target);
}
<html>
 <head>
  <title>Title</title>
 </head>
 <body>
  <form method="POST" action="action.do" onsubmit="return false;">
   <button onclick = "eventHandler(event)">Test</button>
  </form>
 </body>
</html>
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65