如何在我的create.js.erb中重置/清除表单?

时间:2012-07-29 00:08:04

标签: javascript ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-3.1

我无法让我的表单正确重置。它提交并进入数据库,但所有内容都保留在表单上。

这是我的代码:

DogsController

def create
  @dog = current_user.dogs.new(params[:dog])
  if @dog.save
    format.js
  else
    format.js
  end
end

狗/ create.js.erb

$('.add-dog-form').html('<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>');
$('.add-dog-form > form')[0].reset(); // doesn't work

狗/ new.js.erb

$('.add-dog-form').html('<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>');

狗/ _form

<%= form_for(@dog, :remote => true) do |f| %>
   <%= f.label :name, "Name" %>
   <%= f.text_field :name %>
   <%= f.submit "Add Dog" %>
<% end %>

我在宠物视图中创建了狗而不是狗。

PetsController

  def add
    @dog = Dog.new
    @cat = Cat.new
    @bird = Bird.new
  end

宠物/ add.html.erb

点击选项卡,使用Twitter Bootstraps Tabbable Nav ability

将其更改为狗标签
<div class="tabbable">
   <ul class="nav nav-tabs">
      <li class="active">
         <a href="#tab1" data-toggle="tab">Cat</a>
      </li>
      <li>
         <a href="#tab2" data-toggle="tab">Dog</a>
      </li>
      <li>
         <a href="#tab3" data-toggle="tab">Bird</a>
      </li>
   </ul>
   <div class="tab-content">
      <div class="tab-pane active add-cat-form" id="tab1">
         <%= render "cats/form" %>
      </div>
      <div class="tab-pane add-dog-form" id="tab2">
         <%= render "dogs/form" %>
      </div>
      <div class="tab-pane add-bird-form" id="tab3">
         <%= render "birds/form" %>
      </div>
   </div>
</div>

如果表单创建后如何重置表单?

2 个答案:

答案 0 :(得分:7)

尝试给表单一个id:

<%= form_for(@dog, :remote => true, :html => { :id => 'dog_form' } ) do |f| %>

$('#dog_form')[0].reset();

或者,您可以$(":input:not(input[type=submit])").val("");

答案 1 :(得分:0)

好吧我的错误似乎在我自己的文件中。我已经将js文件创建为partials而不是常规页面。即_create.js.erb应为create.js.erb。我还必须在控制器respond_to do |format|操作中添加create。现在我让一切正常。