Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jQuery .on click to Tablesorter th?

I have table.tablesorter element that change frequently using AJAX. I want to add event handler on 'click' that will delegate to table.tablesorter th.class element whenever I click its header. I'm new in use jQuery on. So, I try to put following jQuery script into Chrome Web Console.

jQuery script:

$('#table-content').on(
    'click', 
    '.tablesorter thead tr th', 
    function() {alert(); }
);

My HTML:

<div id="table-content">
    <table class="tablesorter">
        <thead>
            <tr>
                <th class="header">No.</th>
                <th class="header">Name</th>
                <th class="header">Phone</th>
            </tr>
        </thead>
    </table>
</div>

Result: there is no alert pop up window when I click header on the table.

What must I change to show alert dialog when I click the table's header?

like image 898
Ifan Iqbal Avatar asked Nov 02 '22 11:11

Ifan Iqbal


1 Answers

If you are using ajax to load the table, I would recommend one of two things:

  1. Only update the rows within the tbody, unless the header cells are completely being replaced, then you don't need to worry about dealing with the header clicks.

    If you have the tables stored as complete tables, then either follow the other option (recommendation #2), or load the table into a temporary holder, then transfer the tbody and update the table.

    var $table = $('#table-content').find('table');
    $('#hidden-div').load( "ajax.html", function() {
       // remove old tbody
       $table.find('tbody').remove();
       // move new tbody into the initialized tablesorter table
       $('#hidden-div').find('table tbody').appendTo( $table );
       // update tablesorter's cache
       $table.trigger('update');
    });
    
  2. If the entire table is being replaced, just reinitialize tablesorter. Your ajax would look something like this:

    var options = { /* add tablesorter options here */ };
    
    $.ajax({
      url: url,
      data: data,
      success: function(data){
        $('#table-content').find('table').tablesorter(options);
      },
      dataType: dataType
    });
    
like image 154
Mottie Avatar answered Nov 14 '22 05:11

Mottie