Billy Logan
Billy Logan

Reputation: 2520

How to transfer table row into another table using jquery?

I have two tables that contain rows. And I have a javascript function that is supposed to move a table row into the second table. So far, my row addition is being performed with Jquery method closest("tr"). And it seems to work only when each of the tables has at least one row. And when any of tables is empty, it's not working.

Code, that makes rows move.

$(arg).closest("tr").remove()
html=$(arg).closest("tr")

 if(value){
         complete = true;
         $('.completed-tasks').last().after(html)
       }
       else{
         complete = false;
          $('.incompleted-tasks').first().after(html)
        }

Here's the structure of the first table.

  <h3>Completed</h3>
    <table class='table'>

     <% @tasks.complete.each do |task| %>
      <tr class='completed-tasks' id="task_<%= task.id %>">

        <td>
         .
         .
         .
        </td>

     </tr>
    <% end %>

</table>

The second table:

<h3>Incompleted</h3>
  <table class='table'>

   <% @tasks.incomplete.each do |task| %>
    <tr class='incompleted-tasks' id="task_<%= task.id %>">

     <td>
      .
      .
      .
     </td>

    </tr>
  <% end %>

</table>

Any help?

Upvotes: 1

Views: 1453

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074969

The reason that it doesn't work if the target table is empty is that you're targeting rows with statements like:

$('.completed-tasks').last().after(html)

If there are none, you're calling after on an empty set and there's nowhere to put the content.

Instead, target the table:

$(".table").append(html);

or ideally, in your markup, add a tbody in the table, and target that:

$(".table tbody").append(html);

Side note: I wouldn't call the variable containing a jQuery object with a tr element in it html, it's misleading. It's not HTML, it's an object. :-)

Upvotes: 3

dpanshu
dpanshu

Reputation: 463

As per your code, you are first removing the row from the first table and only then copy it to other table. You should instead

html=$(arg).closest("tr")
$(arg).closest("tr").remove()

Upvotes: 1

Related Questions