hellomello
hellomello

Reputation: 8587

Rails: jQuery adding and removing fields in form

I'm trying to add new fields in a form using jQuery.

This is new.html.erb

<%= form_for @hour do |f| %>
  <div id="hourSet">
    <%= render partial: "hours_form" %>
  </div>

  <a href="javascript:;" id="addNewHour">Add Hours</a>

  <div class="hide" id="new_hours_form">
    <%= render partial: "hours_form", locals: {hour: false} %>
  </div>
</div>

js file

$(document).ready ->
  $("#addNewHour").on "click", ->
    $("#hourSet").append $("#new_hours_form").html()

  $("#removeNewHour").on "click", ->
    $("#hourSet").remove()

_hours_form.html.erb

<div class="hoursForm">
  <%= label_tag 'day' %>
  <%= text_field_tag 'day[]' %>
  <%= label_tag 'open_time' %>
  <%= text_field_tag 'open_time[]' %>
  <%= label_tag 'close_time' %>
  <%= text_field_tag 'close_time[]' %>  

  <a href="#" id="removeNewHour">X</a>
</div>

When I'm trying to populate the fields, only the first X works, and it deletes all the fields. I like to only delete 1 at a time. Whats a best method to add unique ids and get those ids for easy removal?

Thanks!

Upvotes: 2

Views: 3153

Answers (3)

dbucki
dbucki

Reputation: 454

try change js

$(document).ready(function(){
  $("#addNewHour").click(function(e){
    e.preventDefault();
    $("#hourSet").append($("#new_hours_form").html());
  });
});

var removeHours = function(elem){
       $(elem).parent().remove();
};

and change html in #removeNewHour -> add attribute onclick="removeHours(this); return false;"

Upvotes: 0

Dave
Dave

Reputation: 4436

Here is the jsfiddle you can refer and alter your code accordingly. I have used closest method of jquery for removel purpose. If this is useful then i don't think there is necessity for unique ids.

$(this).closest('.hoursForm').remove();

Upvotes: 3

roshiro
roshiro

Reputation: 780

The reason the first "X" delete link works is because your javascript attaches the click events at document ready. And at that moment, you just have your first "X" in the screen.

To fix that you can attach events using delegate instead of on. And you shouldn't need to assign id to each X links. Your JS could look like this:

$(document).ready ->
  // Keep the same here
  $("#addNewHour").on "click", ->
    $("#hourSet").append $("#new_hours_form").html()

  // This code below handles the click on the delete link ("X")
  $('.hoursForm').delegate "a", "click", ->
    $(this).parent().remove() 

Hope that works.

Upvotes: 1

Related Questions