SD1990
SD1990

Reputation: 808

The opposite of append in this table using jquery

I need the opposite to this peice of code:

if( $('#effort_<%= @project_task.id %>').length == 0 )
  $('#task_list').append('<tr><td><%= @project_task.project.project_number %> <%= @project_task.project.project_name %> - <%= @project_task.task_name %></td>' +
                         '<td><%= text_field :effort, :hours, :name => 'effort_' + @project_task.id.to_s, :id => 'effort_' + @project_task.id.to_s %></td>' +
                         '<td><%= link_to image_tag('icons/delete.png'), :method => :destroy, :remote => true %></td></tr>' );
  $('#effort_<%= @project_task.id.to_s %>').change( function() { submiteffort( this, <%= @project_task.id.to_s %>); } );

when the user clicks the delete button it needs to delete that row of the table. I know you can use .remove() but im not sure how to use this since im new to RoR.

Upvotes: 2

Views: 897

Answers (4)

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47951

You can do something like this:

$("#task_list a").live("click", function(event) {
  $(event.target).closest("tr").remove();
});

Make sure you use closest. parents will return all the ancestor trs so it might remove more nodes than needed if you have nested tables. closest is the safest option.

Upvotes: 2

Baz1nga
Baz1nga

Reputation: 15579

assuming your delete is inside the tr for each of the rows you need to do something like this

if the close buttton/image has a class close then bind an event on it like this

$('close').live("click",function()
{
    $(this).parents("tr").remove();   //this here is referring to the button 
});

Upvotes: 1

Bas Slagter
Bas Slagter

Reputation: 9929

You can use parent method (add some identifiers) to point to the row you want to delete and than use the remove method to actually remove it.

Upvotes: 0

Henry
Henry

Reputation: 2187

Here is a basic example of how you want to do. I hope you dont mind but I've stripped it down to bare bones but it should give you a good idea of where to begin.

JSFiddle: http://jsfiddle.net/saceh/1/

<button id="Add">Add Row</button>
<hr>
<table id="TaskList">
</table>

<script>
// RowId is not important, just used to show you that rows are dynamically added
var RowId = 0;

$("#Add").click(function (e) {
    $("#TaskList").append("<tr><td>" + RowId  + "</td><td><button id='Delete'>Delete</button></td></tr>");
    RowId++;
});

$("#Delete").click(function(e) {
   var Row = $(this).parents('tr');
   $(Row).remove(); 
});

When delete is clicked it finds the parent row and removes it and Add does something similar to what you are doing at the moment.

Upvotes: 0

Related Questions