How to stop a dynamically loaded form from submitting using jquery?

I am working on an AJAX login system. Right now, when the user clicks on the link, the login form is dynamically loaded when the user clicks on the "login" link. Since I use AJAX for this, I want the form not to submit when the submit button is clicked. I tried the following code as part of the upload function, and the form loads correctly, but the form still submits normally.

$('#loginBox').load('loginform.php'); $('#loginBox form').submit(function(event) { event.preventDefault(); }); 

How can i fix this?

+4
source share
3 answers

jQuery.load is an asynchronous function.

This means that the form may not be available (yet) when you try to match the "#loginBox form". To make sure your code is executed after the form loads, you must pass your code as a callback function to load.

 $('#loginBox').load("form.html", function() { $('#loginBox form').submit(function(event) { event.preventDefault(); }); }); 

Btw - In your case, it doesn't matter if you use event.preventDefault () or return false . Both of them will prevent the submission of your form. (See event.preventDefault () vs return false )

+4
source

Add return false to prevent the default behavior:

 $('#loginBox form').submit(function(event) { return false; }); 
+3
source
  $('#loginBox form').submit(function(event) { return false; }); 
+1
source

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


All Articles