#74 Complex Forms Part 2

See how to use Javascript and RJS to add and remove form fields dynamically. This episode will build upon the previous episode allowing you to create any number of tasks in one form the same time a project is created.
<!-- layouts/application.rhtml -->
<%= javascript_include_tag :defaults %>

<!-- projects/new.rhtml -->
<div id="tasks">
  <%= render :partial => 'task', :collection => @project.tasks %>
</div>
<p><%= add_task_link "Add a task" %></p>

<!-- projects/_task.rhtml -->
<div class="task">
<% fields_for "project[task_attributes][]", task do |task_form| %>
  <p>
    Task: <%= task_form.text_field :name %>
    <%= link_to_function "remove", "$(this).up('.task').remove()" %>
  </p>
<% end %>
</div>
# projects_helper.rb
def add_task_link(name)
  link_to_function name do |page|
    page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
  end
end

你可能感兴趣的:(JavaScript,html,UP)