最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you stop a dynamically loaded form from submitting with jquery? - Stack Overflow

programmeradmin3浏览0评论

I'm working on an AJAX login system. Right now, when the user clicks on a link, the login form is dynamically loaded when the person clicks on a "log in" link. Since I'm using AJAX for this, I want to prevent the form from actually submitting when the submit button is clicked. I tried the following code as part of my load function, and the form loads correctely, but the form still submits normally.

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

How can I fix this?

I'm working on an AJAX login system. Right now, when the user clicks on a link, the login form is dynamically loaded when the person clicks on a "log in" link. Since I'm using AJAX for this, I want to prevent the form from actually submitting when the submit button is clicked. I tried the following code as part of my load function, and the form loads correctely, but the form still submits normally.

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

How can I fix this?

Share Improve this question asked Feb 26, 2011 at 15:17 ZakZak 2,6984 gold badges30 silver badges46 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

jQuery.load is an asynchronous function.

This means that the form may not be available (yet) when you try to match "#loginBox form". To make sure your code is executed after the form is loaded, 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 does not matter wether you use event.preventDefault() or return false. They will both prevent your form from being submitted. (See event.preventDefault() vs. return false)

Add return false to prevent the default behavior:

$('#loginBox form').submit(function(event) {
   return false;
});
    $('#loginBox form').submit(function(event) {
return false;
});
发布评论

评论列表(0)

  1. 暂无评论