Reputation: 2824
I have a form field that I would like to empty immediately the submit. Usually I would do something like:
$("#form").submit(function(e){
e.preventDefault();
$.post(/* custom craft request */);
$("#field").val('');
});
Rails handles all the custom crafting when I add the :remote => true
, but I can't find a way to bind to immediately after the submission.
The documentation ( http://guides.rubyonrails.org/ajax_on_rails.html ) insists there's an ajax:after event, but that doesn't seem to exist. Apparently this documentation is completely outdated, since other functions like remote_form_for don't exist in 3.2
Any help is appreciated. The setTimeout I'm using really doesn't sit well.
EDIT: Adding the working setTimeout solution that I want to replace:
$("#form_id").submit(function(e){
setTimeout(function(){
//this will happen after submission
}, 15);
});
Upvotes: 2
Views: 1910
Reputation: 354
You can attach to ajax callbacks by doing this:
$("#form").bind("ajax:send", function(e){
$("#field").val('');
});
Don't forget to include the rails.js library https://github.com/rails/jquery-ujs
Upvotes: 2
Reputation: 9348
According to the ujs wiki (https://github.com/rails/jquery-ujs/wiki/ajax), all ajax global events are available: http://docs.jquery.com/Ajax_Events
So this should do the trick:
$("#form").bind("ajaxSend", function(){
$("#field").val('');
});
I'm assuming you want the event triggered immediately as the request is sent. Otherwise you can of course use the following to clear the field upon completion (works for failure or success):
$("#form").bind("ajax:complete", function(){
$("#field").val('');
});
Upvotes: 0