Pinal Dave
Pinal Dave

Reputation: 533

Attach jquery plugin function to dynamically created DOM elements

I am using a jQuery plugin to drag table columns to rearrange them as below

$("#myTable").dragtable();

It works fine for existing table and I can drag table columns. However I need to add rows dynamically in myTable but I can't drag dynamically added column.

I looked documentation for .live method but not sure how I would use it in my scenario.

any suggestion ?

Upvotes: 0

Views: 498

Answers (2)

AlmasK89
AlmasK89

Reputation: 1340

You can do like this:

$('.defaultTable').dragtable('destroy').dragtable({});

Full example:

$('.defaultTable').dragtable();
$('#add-column').click(function(e){
      var tbody = $('.defaultTable').find('tbody'),
          thead = $('.defaultTable').find('thead');
          tbody.find('tr').each(function(){
            var tr = $(this);
            tr.append('<td>Some column</td>');
          });
          thead.find('tr').each(function(){
            var tr = $(this);
            tr.append('<th>appended column header</th>');
          });
          $('.defaultTable').dragtable('destroy').dragtable({});
    });
<link href="https://rawgit.com/akottr/dragtable/master/dragtable.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="https://rawgit.com/akottr/dragtable/master/jquery.dragtable.js"></script>
<span id="add-column">Add column</span>

<table class="defaultTable sar-table">
        <thead>
          <tr>
            <th>TIME</th>
            <th>%user</th>
            <th>%nice</th>
            <th>%system</th>
            <th>%iowait</th>
            <th>%idle</th>
          </tr>
        </thead>

        <tbody>
          <tr>
            <td>12:10:01 AM</td><td>28.86</td><td>0.04</td><td>1.65</td><td>0.08</td><td>69.36</td>
          </tr>
          <tr>
            <td>12:20:01 AM</td><td>26.54</td><td>0.00</td><td>1.64</td><td>0.08</td><td>71.74</td>

          </tr>
          <tr>
            <td>12:30:01 AM</td><td>29.73</td><td>0.00</td><td>1.66</td><td>0.09</td><td>68.52</td>
          </tr>
        </tbody>
      </table>

   

Upvotes: 1

sahbeewah
sahbeewah

Reputation: 2690

You can't use .live in this situation. You will have to just call .dragtable() for each new element that you add.

Upvotes: 0

Related Questions