Question

How can I know which submit input is clicked on submit?

For instance, I want to know whether 'update' submit input or 'update_close' submit input is clicked on submit.

html,

<form id="form_data">
    <input type="input" name="title" value="" />
    <input type="submit" name="update" value="Update" />
    <input type="submit" name="update_close" value="Update and Close"/>
</form>

jquery,

$(document).ready(function(){

        $('#form_data').submit(function(e){

            alert($(this).serialize());
            return false;
        });

    });

jsfiddle.

Was it helpful?

Solution

You can't know this in the submit handler. This information is not passed. What you could do is to subscribe to the click events of those 2 buttons and update some global variable or a HTML5 data-* attribute on the form so that inside your form submit handler you will know.

Also if you invoke the .submit event programatically, without clicking on any button, this information simply doesn't make sense.


UPDATE:

Example using HTML5 data-* attributes:

$('#form_data :submit').click(function() {
    $(this).closest('form').data('submitbutton', $(this).attr('name'));
});

and inside your submit handler:

$('#form_data').submit(function(e) {
    var submitButton = $(this).data('submitbutton');
    ...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top