JQuery form submit: Any way to find out which element caused the submit?

I am using asp.net MVC, and when I submit the form, the previous developer built some jQuery validation.

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

The problem is that the "Save" and "Cancel" buttons on the form trigger the jQuery submit function. I do not want the verification logic to be activated if the "Cancel" input button was pressed (id = "cancel" name = "cancel" value = "cancel"). Is there a way so that in this submit function, I can get the identifier, name or value for which the enter button was pressed in order to submit the form?

+4
source share
4 answers

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

The only cross-browser solution I could come up with is the following:

 $(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 you are looking for his answer, but you should change the Cancel button to an anchor label. There is no need to submit a cancellation if you are not doing work on the values โ€‹โ€‹of the form.

+8
source

Well, this will only work if the type button of the enter button looks like this:

 <input type='submit' ... 

so make sure the cancel button does not have type='submit' and it should work

0
source
 var myForm = $('form'); $('input[type="submit"]',myForm).click(function(e) { var whoClickedsubmit = $(e.target); //further, you can use .attr('id') //do other things here }); 

EDIT

 .submit(function(event){ var target = event.originalEvent.explicitOriginalTarget.value; //But IE does not have the "explicitOriginalTarget" property }); 
0
source

EDIT

This only works in FF and not in Chrome (and I, I think, not in other WebKit-based browsers), so I just leave it here as a browser, a workaround, an interesting note, but not as an answer.


@ An ideal suggestion NOT to make submit type cancel buttons is perhaps the cleanest way. However, if you SHOULD do it the way you do it now:

 $('form').submit(function(e){ if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){ //don't validate } else{ //validate } }); 
0
source

Source: https://habr.com/ru/post/1347800/


All Articles