McTrafik McTrafik - 3 months ago 15
HTML Question

Form onSubmit determine which submit button was pressed

I have a form with two submit buttons and some code:

HTML:

<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />


Javascript:

form.onSubmit = function(evnt) {
// Do some asyncrhnous stuff, that will later on submit the form
return false;
}


Of course the two submit buttons accomplish different things. Is there a way to find out in
onSubmit
which button was pressed, so later I could submit by doing
thatButton.click()
?

Ideally I would like to not modify the code for the buttons, just have a pure-javascript addon that has this behavior.

I know that FF has
evnt.explicitOriginalTarget
but I can't find anything for other browsers.

Answer

Not in the submit event handler itself, no.

But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.

Here's a full example (using jQuery for brevity)

<html>
<head>
  <title>Test Page</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">

  jQuery(function($) {
      var submitActor = null;
      var $form = $('#test');
      var $submitActors = $form.find('input[type=submit]');

      $form.submit(function(event) {
          if (null === submitActor) {
              // If no actor is explicitly clicked, the browser will
              // automatically choose the first in source-order
              // so we do the same here
              submitActor = $submitActors[0];
          }

          console.log(submitActor.name);
          // alert(submitActor.name);

          return false;
      });

      $submitActors.click(function(event) {
          submitActor = this;
      });
  });

  </script>
</head>

<body>

  <form id="test">

    <input type="text" />

    <input type="submit" name="save" value="Save" />
    <input type="submit" name="saveAndAdd" value="Save and add another" />

  </form>

</body>
</html>
Comments