views:

437

answers:

4

I have a form which gets introduced via XHR and I need to be able to bind an event on it, for submit. I've downloaded the jquery.form.js plugin. What's the best way to perform a late binding so that I can do something such as:

 $(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function() { 
            alert("Thank you for your comment!"); 
        }); 
    });

Unfortunately since the form isn't readily available when the DOM first populates, this won't work.

** EDIT **

I've tried binding to the form AFTER it is retrieved via XHR and haven't had much luck. Here's how it looks:

 $.get("foo.php", function(data) { 
    $('#my_form').ajaxForm(function() { 
         alert("Thank you for your comment!"); 
     });
});
A: 

Perform the binding on the XHR request callback.

jonstjohn
I've tried binding it once it has already been brought back into the DOM without much luck.
Coocoo4Cocoa
+2  A: 

jQuery 1.3 introduced "Live" events, which will bind to any current, and future element defined by a selector.

I've not done anything with them, but it seems reasonable that you should be able to do something like:

$(document).ready(function() {
    $('form').live("ready",function() {
        alert("Something");
    });
});

Not sure if the ready event would actually work in this case, but seems worth a shot.

ckramer
A: 

Bind the event just after load the form via XHR.

+1  A: 

I think you don't do it right. The way I use jquery forms is this:

$('#myform').submit(function(){
 $(this).ajaxSubmit(function(){
  alert('Thanks for your comment');
 });
 return false
});

You call this after the form is injected into DOM. Another way to do this is to using live binding from jquery

$('#myform').live('submit', function(){
 $(this).ajaxSubmit(function(){
  alert('Thanks for your comment');
 });
 return false
});

Any way you pick, you must include this piece of code into $(document).ready()

Ionut Staicu
Thanks, that did the trick
Coocoo4Cocoa
jQuery docs said that live() on submit is not supported.
Elzo Valugi