Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Rails remote form after submitting

I'm using Rails 3 with jQuery, and have a simple form with a single text input and a submit button. I have the form submitting with :remote => true, and would like to clear the input after the form is submitted. I tried this jQuery code:

$('#new_message').submit(function() {
  $('#message_content').val('');
});

However, this clears the input before the form is submitted, so I end up submitting a blank form.

After searching around a bit, I also tried the following version:

$('#new_message').submit(function(e) {
  e.preventDefault();
  this.submit();
  $('#message_content').val('');
});

...but this seems to override the :remote => true magic, and the form gets submitted with a full page reload. Any ideas?

like image 840
DigitalCora Avatar asked May 19 '11 02:05

DigitalCora


2 Answers

When submit button is pressed for a form marked remote => true, javascript code in rails.js does the submit(). You need not override the functionality.

Try this instead in $(document).ready -

(Edit: Using bind instead of live. Thanks Darren Hicks.)

$("#new_message").bind("ajax:complete", function(event,xhr,status){
  $('#message_content').val('');
}

This adds an event handler for the ajax:complete event. This event is fired when your the ajax-submit-form is completed. More here.

Edit:

Don't forget closing ) on the bind method.

$("#new_message").bind("ajax:complete", function(event,xhr,status){
   $('#message_content').val('');
 })
like image 61
abhishek Avatar answered Sep 20 '22 15:09

abhishek


In your action.js.erb file

$('#message_content').attr('value','');

Where action is the method name (which you don't state in your question) in your controller

like image 28
Nick Avatar answered Sep 20 '22 15:09

Nick