提交后清除Rails远程表单 [英] Clear Rails remote form after submitting

查看:77
本文介绍了提交后清除Rails远程表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Rails 3与jQuery结合使用,并且具有一个简单的表单,其中包含单个文本输入和一个提交按钮.我有使用:remote => true提交的表单,并且想在提交表单后清除 的输入.我尝试了以下jQuery代码:

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('');
});

...但是这似乎覆盖了:remote => true魔术,并且表单在重新加载整个页面后就提交了.有什么想法吗?

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

推荐答案

当按下提交按钮标记为remote => true的表单时,rails.js中的javascript代码将执行submit().您无需覆盖功能.

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.

$(document).ready-

(使用bind而不是live.感谢Darren Hicks.)

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

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

这将为ajax:complete事件添加一个事件处理程序.当您的ajax-submit-form完成时,将触发此事件. 此处.

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

这篇关于提交后清除Rails远程表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆