4

I can't get my form to reset correctly. It submits and it goes to the database but everything remains on the form.

Here is my code:

DogsController

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

dog/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

dog/new.js.erb

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

dogs/_form

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

I create dogs at the Pets view instead of the dogs.

PetsController

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

pets/add.html.erb

I click on the tab which changes it to the Dog Tab using 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>

How can I reset the form if it gets created?

4

2 回答 2

8

尝试给表单一个 id:

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

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

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

于 2012-07-29T12:19:59.247 回答
0

好吧,看来我的错误在于我的文件本身。我已将 js 文件创建为部分而不是常规页面。即_create.js.erb应该是create.js.erb。我还必须添加respond_to do |format|控制器create动作。现在我让一切正常工作。

于 2012-07-29T18:10:57.797 回答