Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset/clear form within my create.js.erb?

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?

like image 329
LearningRoR Avatar asked Feb 20 '23 17:02

LearningRoR


1 Answers

Try giving the form an id:

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

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

Alternatively, you can do $(":input:not(input[type=submit])").val("");.

like image 69
Syed Aslam Avatar answered Feb 28 '23 04:02

Syed Aslam