tags:

views:

352

answers:

3

I'm a jQuery newbie, and I have trouble with a little script I created.

First of all, I have a table with 5 default rows. These are sortable, using a plugin called "Table Drag'n'Drop". A column in that table consists of a linked X which removes the table row when clicked.

The table looks like this:

<table id="tracks">
  <thead>
    <tr>
      <th>Title</th>
      <th>File</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr class="track">
      <td><input type="text" /></td>
      <td><input type="file" /></td>
      <td><a href="#" class="deleteme">X</a></td>
    </tr>
  </tbody>
</table>

The tr.track repeats itself five times in the code. These are perfectly draggable and removable by clicking the X.

This is the jQuery code:

// makes the table sortable
$("#tracks").tableDnD();

// adds more rows (just a link)
$("#addRow").click(function() {
    newTrack = 'same code as tr.track'
    $("tbody").append(newTrack);
    return false;
});

// delete rows
$("a.deleteme").click(function() {
    $(this).parents("tr.track").fadeOut("fast", function() {
        $(this).remove();
        return false;
    });
});

When I add a new table row, this row won't let it sort or be removed by clicking the X. Seems like the jQuery doesn't notices it's there?

+5  A: 

You need to use live:

Binds a handler to an event (like click) for all current - and future - matched element.

Sounds like a winner. So just replace this line:

$("a.deleteme").click(function() {

With this, using live instead:

$("a.deleteme").live('click', function() {

Edit:

As far as the sorting, apparently the plugin you are using is not taking advantange of live internally. The only solution is then to call the init code again after you add a new table row. You can do this fine with some plugins and some others don't handle it nicely. Let us know how it goes. Just add this:

$("#tracks").tableDnD();

Inside the #addMore click handler, after you append newTrack.

Paolo Bergantino
I took too long finding the link to live you beat me to it.
RedWolves
Thanks, that made it work! The only thing is that the row isn't sortable anymore.
rebellion
The DnD plugin must not use live internally. You need to call $("#tracks").tableDnD(); again.
Paolo Bergantino
+1  A: 

You need to use live to bind current and future elements to events.

RedWolves
Thanks for your quick reply, you guys are fast!
rebellion
+1  A: 

You have to refresh the Sortable in JQuery.

$("#tracks").sortable("refresh");

This is assuming that you are using out of the box Sortable plugin. .tableDnD looks like an custom extension method.

nuhusky2003