Alex
Alex

Reputation: 8663

jQuery re-bind .submit() after AJAX call

I'm creating a forum-style system where posts are created and users can then post comments on the original post. (What I'm doing is actually very different in context but the theme is the same).

The form to add a comment is part of the Post, which is pulled in using jQuery $.get().

Here's the submit handler currently:

$('#add-stage-form').submit(function(){

        var data = $('#add-stage-form').serialize();
        add_stage(data);
        return false;   
    });

Okay.. now, I need that to be re-bound once it's pulled in, in the same was live() can be used.

And please, if anybody suggests live('submit', function(){ ... }) I WILL scream because submit doesn't work like click!

I am also well aware that you I could bind the 'click' event on the same button - I'd much rather bind the .submit() event though, if possible

Thanks in advance! :)

Upvotes: 3

Views: 1532

Answers (2)

Dean North
Dean North

Reputation: 3780

You can add the binding manually in the onComplete callback of the get method...

$.get('getposts.html', function(data) {
    var myForm = $(data);
    $('.formContainer').append(myForm);

    $('.add-stage-form', myForm).submit(function(){

        var data = $(this).serialize();
        add_stage(data);
        return false;   
    });

});

*edit Changed add-stage-form to be a class rather than an id. You mentioned there will be a form per post?

Upvotes: 5

griegs
griegs

Reputation: 22760

Have you tried using Live()? :)

But seriously, it might not be such a bad idea if you attach a click event to the button which then calls a jQuery.Post() opperation. Or even a javascript method that submits the page.

I know this is not the (best) solution but it might get you over the line.

I'll retract this answer if a better one comes along.

Upvotes: 1

Related Questions