Can I determine which Submit button was used in javascript?

Some browsers (at least Firefox, Opera and IE) support this:

<script type="text/javascript">
function checkForm(form, event) {
    // Firefox || Opera || IE || unsupported
    var target = event.explicitOriginalTarget || event.relatedTarget ||
        document.activeElement || {};

    alert(target.type + ' ' + target.value);
    return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
   <input type="text" name="tagName" size="30" value="name goes here" />
   <input type="hidden" name="tagID" value="1" />
   <input type="submit" name="submit" value="Change" />
   <input type="submit" name="submit" value="Delete" />
</form>

For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.


Here's an unobtrusive approach using jQuery...

$(function ()
{
    // for each form on the page...
    $("form").each(function ()
    {
        var that = $(this); // define context and reference

        /* for each of the submit-inputs - in each of the forms on
           the page - assign click and keypress event */
        $("input:submit", that).bind("click keypress", function ()
        {
            // store the id of the submit-input on it's enclosing form
            that.data("callerid", this.id);
        });
    });


    // assign submit-event to all forms on the page
    $("form").submit(function ()
    {
        /* retrieve the id of the input that was clicked, stored on
           it's enclosing form */
        var callerId = $(this).data("callerid");

        // determine appropriate action(s)
        if (callerId == "delete") // do stuff...

        if (callerId == "change") // do stuff...

        /* note: you can return false to prevent the default behavior
           of the form--that is; stop the page from submitting */ 
    });
});

Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.


You could also use the onclick event in a number of different ways to address the problem.

For instance:

<input type="submit" name="submit" value="Delete" 
       onclick="return TryingToDelete();" />

In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.

Tags:

Javascript