1
votes

I am using Motties fork of the tablesorter plugin tablesorter with the input parser widget as well as the grouping widget set in options. I need to perform an ajax call to initilise the table on the second fieldset of a form that passes the values from the first fieldset and displays the corresponding rows from the datbase. This works as expected but the functionality of the table sorter on inputs no longer works after the AJAX load.

I can get static tables to sort correctly, however my table loaded via AJAX does not sort my checkbox column correctly. I can see in the DOM that it the widget functionality isn't being called as the "checked" and "checked-0" classes are not being added to the TR like they are with my static versions.

From my searches I have tried updating the table after the AJAX call but to no affect.

if (tableInitilised == false){
      $('#show').load(('ajax/field2.php?country='+$("#p_country").val()+'&category='+$("#p_vid_category").val()+'&system='+$("#p_vid_res").val()), function() {
        /* When load is done */
        loadTable();
        var resort = true,
                callback = function(){ console.log('table updated'); };
        $('#playlistCreationForm-table').trigger("update", [ resort, callback ]);
      });

    }
    function loadTable()
    {
      //jQuery("#playlistCreationForm-table").trigger('updateCell');
      $('#playlistCreationForm-table').tablesorter({

        // hidden filter input/selects will resize the columns, so try to minimize the change
        widthFixed : false,

        headers: {
          0: { sorter: "checkbox" },
          1: { sorter: "inputs" }
        },

        // initialize zebra striping and filter widgets
        widgets: [ "group", "filter", "zebra","stickyHeaders" ],

        ignoreCase: false,

        widgetOptions : {


          // filter_anyMatch options was removed in v2.15; it has been replaced by the filter_external option

          // If there are child rows in the table (rows with class name from "cssChildRow" option)
          // and this option is true and a match is found anywhere in the child row, then it will make that row
          // visible; default is false
          filter_childRows : false,

          // if true, filter child row content by column; filter_childRows must also be true
          filter_childByColumn : false,

          // if true, include matching child row siblings
          filter_childWithSibs : true,

          // if true, a filter will be added to the top of each table column;
          // disabled by using -> headers: { 1: { filter: false } } OR add class="filter-false"
          // if you set this to false, make sure you perform a search using the second method below
          filter_columnFilters : true,

          // if true, allows using "#:{query}" in AnyMatch searches (column:query; added v2.20.0)
          filter_columnAnyMatch: true,

          // extra css class name (string or array) added to the filter element (input or select)
          filter_cellFilter : '',

          // extra css class name(s) applied to the table row containing the filters & the inputs within that row
          // this option can either be a string (class applied to all filters) or an array (class applied to indexed filter)
          filter_cssFilter : '', // or []

          // add a default column filter type "~{query}" to make fuzzy searches default;
          // "{q1} AND {q2}" to make all searches use a logical AND.
          filter_defaultFilter : {},

          // filters to exclude, per column
          filter_excludeFilter : {},

          // jQuery selector (or object) pointing to an input to be used to match the contents of any column
          // please refer to the filter-any-match demo for limitations - new in v2.15
          filter_external : '',

          // class added to filtered rows (rows that are not showing); needed by pager plugin
          filter_filteredRow : 'filtered',

          // ARIA-label added to filter input/select; {{label}} is replaced by the column header
          // "data-label" attribute, if it exists, or it uses the column header text
          filter_filterLabel : 'Filter "{{label}}" column by...',

          // add custom filter elements to the filter row
          // see the filter formatter demos for more specifics
          filter_formatter : null,

          // add custom filter functions using this option
          // see the filter widget custom demo for more specifics on how to use this option
          filter_functions : null,

          // hide filter row when table is empty
          filter_hideEmpty : false,

          // if true, filters are collapsed initially, but can be revealed by hovering over the grey bar immediately
          // below the header row. Additionally, tabbing through the document will open the filter row when an input gets focus
          // in v2.26.6, this option will also accept a function
          filter_hideFilters : false,

          // Set this option to false to make the searches case sensitive
          filter_ignoreCase : true,

          // if true, search column content while the user types (with a delay).
          // In v2.27.3, this option can contain an
          // object with column indexes or classnames; "fallback" is used
          // for undefined columns
          filter_liveSearch : true,

          // global query settings ('exact' or 'match'); overridden by "filter-match" or "filter-exact" class
          filter_matchType : { 'input': 'exact', 'select': 'exact' },

          // a header with a select dropdown & this class name will only show available (visible) options within that drop down.
          filter_onlyAvail : 'filter-onlyAvail',

          // default placeholder text (overridden by any header "data-placeholder" setting)
          filter_placeholder : { search : '', select : '' },

          // jQuery selector string of an element used to reset the filters
          filter_reset : 'button.reset',

          // Reset filter input when the user presses escape - normalized across browsers
          filter_resetOnEsc : true,

          // Use the $.tablesorter.storage utility to save the most recent filters (default setting is false)
          filter_saveFilters : true,

          // Delay in milliseconds before the filter widget starts searching; This option prevents searching for
          // every character while typing and should make searching large tables faster.
          filter_searchDelay : 300,

          // allow searching through already filtered rows in special circumstances; will speed up searching in large tables if true
          filter_searchFiltered: true,

          // include a function to return an array of values to be added to the column filter select
          filter_selectSource  : null,

          // if true, server-side filtering should be performed because client-side filtering will be disabled, but
          // the ui and events will still be used.
          filter_serversideFiltering : false,

          // Set this option to true to use the filter to find text from the start of the column
          // So typing in "a" will find "albert" but not "frank", both have a's; default is false
          filter_startsWith : false,

          // Filter using parsed content for ALL columns
          // be careful on using this on date columns as the date is parsed and stored as time in seconds
          filter_useParsedData : false,

          // data attribute in the header cell that contains the default filter value
          filter_defaultAttrib : 'data-value',

          // filter_selectSource array text left of the separator is added to the option value, right into the option text
          filter_selectSourceSeparator : '|',

          group_collapsible : true,  // make the group header clickable and collapse the rows below it.
          group_collapsed   : false, // start with all groups collapsed (if true)
          group_saveGroups  : true,  // remember collapsed groups
          group_saveReset   : '.group_reset', // element to clear saved collapsed groups
          group_count       : " ({num})", // if not false, the "{num}" string is replaced with the number of rows in the group

          // apply the grouping widget only to selected column
          group_forceColumn : [],   // only the first value is used; set as an array for future expansion
          group_enforceSort : true, // only apply group_forceColumn when a sort is applied to the table

          // checkbox parser text used for checked/unchecked values
          group_checkbox    : [ 'selected', 'unselected' ],

          // change these default date names based on your language preferences (see Globalize section for details)
          group_months      : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ],
          group_week        : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
          group_time        : [ "AM", "PM" ],

          // use 12 vs 24 hour time
          group_time24Hour  : false,
          // group header text added for invalid dates
          group_dateInvalid : 'Invalid Date',

          // this function is used when "group-date" is set to create the date string
          // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString()
          // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter
          group_dateString  : function(date) {
            return date.toLocaleString();
          },

          group_formatter   : function(txt, col, table, c, wo, data) {
            // txt = current text; col = current column
            // table = current table (DOM); c = table.config; wo = table.config.widgetOptions
            // data = group data including both group & row data
            if (col === 7 && txt.indexOf("GMT") > 0) {
              // remove "GMT-0000 (Xxxx Standard Time)" from the end of the full date
              // this code is needed if group_dateString returns date.toString(); (not localeString)
              txt = txt.substring(0, txt.indexOf("GMT"));
            }
            // If there are empty cells, name the group "Empty"
            return txt === "" ? "Empty" : txt;
          },

          group_callback    : function($cell, $rows, column, table) {
            // callback allowing modification of the group header labels
            // $cell = current table cell (containing group header cells ".group-name" & ".group-count"
            // $rows = all of the table rows for the current group; table = current table (DOM)
            // column = current column being sorted/grouped
            if (column === 9) {
              $cell.find(".group-name").append(" seconds");
            }
            if (column === 2) {
              $cell.find(".group-name").append("s");
            }
          },
          // event triggered on the table when the grouping widget has finished work
          group_complete    : "groupingComplete"
        }
      });
      initiliseOrderColumn();
      jQuery("#playlistCreationForm-table").trigger('updateCell');
      tableInitilised = true;
    }

function initiliseOrderColumn()
{
  runcheck();
  $('input[type=checkbox]').on('input', function()
    {
      runcheck();
  });
  function runcheck()
  {
    $('.order-cell input').each(function(){
      //if statement here 
      // use $(this) to reference the current div in the loop
      var numberincount = 0;
      // checks if checkbox one column over is checked (i.e. select checkbox)
      if($(this).parent().prev().children().children().is(':checked')){
        /////////////////////////////////////////////////////////////
        // This is all WTF code
        numberincount++;
        if(numberOfSelectedVideos < numberincount)
        {
          numberOfSelectedVideos = numberincount;
          checkboxvalidation.push($(this).val());
        }else
        {

        }
        //////////////////////////////////////////////////////////////
        //if checked shows input box for ordering
        $(this).addClass('selected').removeClass('not-selected');
      }else
      {
        //else hides input box and clears value or order input
        $(this).addClass('not-selected').removeClass('selected').val('');
      }
    });
  }
}

Update:

Ive been trying to troubleshoot this more today to no avail. I've turned on the debugging option the console table printed when detecting parsers for each columns assigns the correct parser for each column. I am recreating a condensed version to post here.

--

If someone could point me in the right direction here I would appreciate it.

Thanks,

1

1 Answers

0
votes

Eventually found the solution to my problem in the tablesorter docs loading via ajax

my issue was trying to load the whole table via ajax and then initilising it. changed my ajax request to only return the inner html of tbody. I could then initilise the table on page load on then append the data to the tbody and call a tablesort update successfully

$(document).ready(function(){
    $('table').tablesorter({

        debug : false,

        // hidden filter input/selects will resize the columns, so try to minimize the change
        widthFixed : true,

        headers: {
            0: { sorter: "checkbox" },
            1: { sorter: "inputs" }
        },

        // initialize zebra striping, filter, sticky headers and grouping widgets
        widgets: [ "group", "columns", "filter", "zebra","stickyHeaders" ],

        // checkbox parser text used for checked/unchecked values
        group_checkbox    : [ 'selected', 'unselected' ],

        group_formatter   : function(txt, col, table, c, wo, data) {
            // txt = current text; col = current column
            // table = current table (DOM); c = table.config; wo = table.config.widgetOptions
            // data = group data including both group & row data
            if (col === 7 && txt.indexOf("GMT") > 0) {
            // remove "GMT-0000 (Xxxx Standard Time)" from the end of the full date
            // this code is needed if group_dateString returns date.toString(); (not localeString)
            txt = txt.substring(0, txt.indexOf("GMT"));
            }
            // If there are empty cells, name the group "Empty"
            return txt === "" ? "Empty" : txt;
        },

        group_callback    : function($cell, $rows, column, table) {
            // callback allowing modification of the group header labels
            // $cell = current table cell (containing group header cells ".group-name" & ".group-count"
            // $rows = all of the table rows for the current group; table = current table (DOM)
            // column = current column being sorted/grouped
            if (column === 10) {
            $cell.find(".group-name").append(" seconds");
            }
            if (column === 2) {
            $cell.find(".group-name").append("s");
            }
        },
        // event triggered on the table when the grouping widget has finished work
        group_complete    : "groupingComplete"
        }

    });
    ///END tablesorter initilisationg


    $( ".nextbtn" ).on('click', function(){
        if (fieldsetPos == 1)
        {
          showPage2();
          fieldsetPos = 2;
      });

    function showPage2()
    {
        if (tableInitilised == false){

            $.tablesorter.clearTableBody( $("table") ); 

            $.get('ajax/field2.php?country='+$("#p_country").val()+'&category='+$("#p_vid_category").val()+'&system='+$("#p_vid_res").val(), function(php) {

                // append the "ajax'd" data to the table body
                $("table tbody").append(php);

                // let the plugin know that we made a update
                // the resort flag set to anything BUT false (no quotes) will trigger an automatic
                // table resort using the current sort
                var resort = true;
                $("table").trigger("update", [resort]);
                $('table').trigger('applyWidgets');
                tableInitilised = true;
                recreateTable = false;


                //Run Order-cell Hide/Show function
                initiliseOrderColumn();

              });
            // 
        }
        //Show Pages
        $( ".field1" ).hide();
        $( ".field3" ).hide();
        $( ".field2" ).show();
    }
});