Submitting a form in plain js does not trigger jquery related events

I have code like this

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $("#main_form").submit(function(){ alert("submitting"); }); $("#main_form").on("submit", function(){ alert("ON submitting"); }); $("#lnk").click(function(){ //$("#main_form").submit(); //when submitting like this - event is triggered document.getElementById("main_form").submit(); //no submitting alerts are triggered }); }); </script> <h4><?php echo time(); ?></h4> <form id="main_form" action=""> <input type="text" value="x"/> <input type="submit" value="submit-btn"/> </form> <a id="lnk" href="#">test submit js</a> 

When I click the "Send" button, I get 2 warnings, so the onsubmit events are fired, but when I click the #lnk link, which should be sent using simple js, for example

  document.getElementById("main_form").submit(); 

I get only a view of the form, but no warnings. But when I uncomment sending via jquery

 $("#main_form").submit(); 

warnings are returned again. Can someone explain to me why this is?

PS I have legacy code that submits the form in plain js, and I would prefer not to change it, so I decided to just bind the onsubmit events and perform some checks in the user-defined function, but I had the problem described above

+4
source share
2 answers

Browsers do not fire the onsubmit event of an element when the submit () method is called. When you use jQuery().trigger("submit") , jQuery calls the native submit() method for you, but since it does not "see" its own event and the native submit() does not fire native onsubmit, it is not called. However, this is a browser quirk and outside of jQuery.

+3
source

I think the problem is related to the fact that events are raised only when the user has iteration from the user, which means that they cannot be called automatically when they are activated from the code.

By the way, the following code snippets are the same:

 $("#main_form").submit(function(){ alert("submitting"); }); $("#main_form").on("submit", function(){ alert("ON submitting"); }); 

They both fire when the submit event occurs.

You can check this out: http://james.padolsey.com/jquery/#v=git&fn=jQuery.fn.submit

0
source

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


All Articles