开发者

jquery: duplicated submit occurrences when the same form is loaded through ajax

I have a global form which I want to use the same form every time on submit, and this form is auto generated depends on how many threads are produced from the database. so I might a two or four form of the same kind when the page is loaded. Also, this type of form will be loaded onto the page on certain request through ajax. and the most important is - all the开发者_运维技巧se form will use the same submit function.

for instance,

the html

<div class="form"></div>
<a href="form.php" class="load">load</a>

<div>
<form action="#" method="post" enctype="multipart/form-data" class="form-global">
    <textarea name="str_content" title="Write a comment..."></textarea>
    <input type="submit" name="submit" value="SUBMIT" class="button-public left"/>
</form>
</div>

<div>
<form action="#" method="post" enctype="multipart/form-data" class="form-global">
    <textarea name="str_content" title="Write a comment..."></textarea>
    <input type="submit" name="submit" value="SUBMIT" class="button-public left"/>
</form>
</div>

below is the working code in jquery,

$(document).ready(function() {

    sumbitform();

    $(".load").click(function () {
        var path = $(this).attr('href');

        $('.form').load( path, {}, function(){

            sumbitform();

            //$(this).bind("submit", sumbitform);
        });

        return false;
    });


});

this.sumbitform = function(){

    $("form.form-global").submit(function(){
        alert('1');
        return false;
    });
}

all the forms work as normal when the page is loaded, the submit only happens once on each form. but the problem occurs whenever a new form of the same kind is loaded through ajax, the other existing forms will trigger twice.

you can see problem on this link, http://nano-visions.net/dump/jquery.ajaxsubmit/

how can I resolve this problem? can I attach the submit function to the ajax loaded form only like this line below?

$(this).bind("submit", sumbitform); // doesn't work obviously

or any other better ideas?

thanks.


You need to use $(this).live("submit", sumbitform); instead. This will bind the same event to elements which appear later on, not just the ones which are around right now.

For more info check out live in the jQuery docs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜