Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery form submit: Any way to know what element triggered the submit?

I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel"). Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

like image 850
ghost_mv Avatar asked Feb 24 '23 12:02

ghost_mv


1 Answers

I asked this same question: How can I get the button that caused the submit from the form submit event?

The only cross-browser solution I could come up with was this:

$(document).ready(function() {
    $("form").submit(function() { 

    var val = $("input[type=submit][clicked=true]").val()

    // DO WORK

});

$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.

like image 138
hunter Avatar answered May 15 '23 14:05

hunter