2014-07-18 11 views
5

Zaimplementowałem jQuery tablesorter w moim projekcie.Sortownik tabel jQuery nie działa dla wartości pobranych przez AJAX

Moja tabela składa się z pól tekstowych wejściowych, z których niektóre są wypełniane przez ajax. Sortowanie tabel działa doskonale dla pól wejściowych wprowadzanych przez użytkownika, ale pola wejściowe zapełniane z bazy danych przy użyciu ajax nie sortują poprawnie.

Mój kod:

jQuery(function() { 
    jQuery('#tablesorter-demo').tablesorter({ 
     widgets: ['zebra', 'stickyHeaders'], 
     headers: { 
      2: { 
       sorter: 'inputs' 
      }, 
      3: { 
       sorter: 'inputs' 
      }, 
      5: { 
       sorter: 'inputs' 
      } 
     } 
    }); 
}); 

jQuery.tablesorter.addParser({ 
    id: 'inputs', 
    is: function (s) { 
     return false; 
    }, 
    format: function (s, table, cell, cellIndex) { 
     var jQueryc = jQuery(cell); 

     // return 1 for true, 2 for false, so true sorts before false 
     if (!jQueryc.hasClass('updateInput')) { 
      jQueryc 
       .addClass('updateInput') 
       .bind('keyup', function() { 
        console.log(table); 
        jQuery(table).trigger('updateCell', [cell, false]); // false to prevent resort 
       }); 
     } 
     return jQueryc.find('input[type="text"]').val(); 
    }, 
    type: 'text' 
}); 

Moja funkcja AJAX:

jQuery('.bulkupload').keyup(function() { 
    check = 1; 
    jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F"); 
    var part_no1 = jQuery("#" + jQuery(this).attr("id")).val(); 
    var fieldcount = part_no1.toString().length; 
    var thenum = jQuery(this).attr("id").replace(/^\D+/g, ''); 

    if (jQuery('#qty' + thenum).val() == '') { 
     jQuery('#qty' + thenum).val('Enter Quantity'); 
     jQuery('#qty' + thenum).css("color", "#DF1F26"); 
    } 

    var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails"; 
    jQuery.ajax({ 
     type: "POST", 
     url: url1, 
     data: { 
      part_no1: part_no1 
     }, 
     success: function (response) { 
      if (response == "check") { 
       jQuery('#item_name' + thenum).val("Not Found"); 
       jQuery('#item_desc' + thenum).val("Not Found"); 
       jQuery('#av_qty' + thenum).css("color", "#DF1F26"); 
       jQuery('#item_name' + thenum).css("color", "#DF1F26"); 
       jQuery('#item_desc' + thenum).css("color", "#DF1F26"); 
       jQuery('#brand_name' + thenum).css("color", "#DF1F26"); 
      } 
      else { 
       var result1 = jQuery.parseJSON(response); 

       jQuery('#item_name' + thenum).val(result1.prodname1); 
       jQuery('#item_desc' + thenum).val(result1.productdescription1); 
       jQuery('#brand_name' + thenum).val(result1.brand); 
       jQuery('#av_qty' + thenum).css("color", "#DF1F26"); 
       jQuery('#item_name' + thenum).css("color", "#DF1F26"); 
       jQuery('#item_desc' + thenum).css("color", "#DF1F26"); 
       jQuery('#brand_name' + thenum).css("color", "#DF1F26"); 
       if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) { 
        jQuery('#av_qty' + thenum).val("Not in Stock"); 
       } else { 
        jQuery('#av_qty' + thenum).val(result1.stock); 
       } 

       jQuery("#tablesorter-demo").trigger('updateCell'); 
      } 
     } 
    }); 
}); 

Odpowiedz

2

z opcji & widżety, że używasz, wydaje się, że w rzeczywistości za pomocą mojego fork of tablesorter zamiast oryginalnej wtyczki.

W każdym razie, stworzony dla parsera wejściowego widget jest wiązanie się z komórką

jQuery(cell).bind('keyup', function() { ... } 

ale gdy stół jest posortowana, komórki są usuwane z tbody powodując jakieś powiązania zdarzeń do złamania.Sposobem na obejście tego problemu jest użycie delegated event binding na tbody (ale zrobione poza funkcją widżetu format funkcja, ponieważ trzeba to zrobić tylko raz).

jQuery('table tbody').on('keyup', 'input', function(e) { 
    var $input = $(e.target); 
    ... 
} 

Dodatkowo, gdy wiele wejść z rozmowy ajax zaktualizować, byłoby lepiej po prostu zaktualizować je wszystkie na raz (.trigger('update')), inaczej używasz metody updateCell zbyt dużo i prawdopodobnie powodując cały proces trwa dłużej niż to konieczne.

This demo używa bardzo podobnej metody do aktualizacji pól wyboru w tabeli, więc powinno być dość proste przekonwertowanie go, aby działał z wartościami wejściowymi - jeśli masz problemy, po prostu post tutaj, a pomogę.

// checkbox parser 
$.tablesorter.addParser({ 
    id: 'checkbox', 
    is: function(s) { 
     return false; 
    }, 
    format: function(s, table, cell) { 
     var $c = $(cell).find('input'); 
     return $c.length ? $c.is(':checked') ? 1 : 2 : s; 
    }, 
    type: 'numeric' 
}); 

$(function() { 
    // using .on() which requires jQuery 1.7+ 
    $('table').on('tablesorter-initialized', function() { 

     // class name to add on tr when checkbox is checked 
     var highlightClass = 'checked', 
     // resort the table after the checkbox is modified? 
     resort = true, 
     // if a server side database needs to be updated, do it here 
     serverCallback = function(table, inputElement) {}, 

     $table = $(this), 
     c = this.config, 
     wo = c && c.widgetOptions, 
     // include sticky header checkbox; if installed 
     $sticky = c && wo.$sticky || '', 
     doChecky = function(c, col) { 
      $table 
       .children('tbody') 
       .children('tr:visible') 
       .children('td:nth-child(' + (parseInt(col, 10) + 1) + ')') 
       .find('input') 
       .each(function() { 
        this.checked = c; 
        $(this).trigger('change'); 
       }); 
     }; 

     $table 
      .children('tbody') 
      .on('change', 'input', function() { 
       // ignore change if updating all rows 
       if ($table[0].ignoreChange) { return; } 
       var col, $this = $(this); 
       $this.closest('tr').toggleClass(highlightClass, this.checked); 
       $this.trigger('updateCell', [ $this.closest('td'), resort ]); 
       // if your server side database needs more parameters, add them here sent to the callback 
       serverCallback($table[0], this); 
       // uncheck header if any checkboxes are unchecked 
       if (!this.checked) { 
        $table.add($sticky).find('thead input').prop('checked', false); 
       } 
      }) 
      .end() 
      .add($sticky) 
      .find('thead input') 
      // Click on checkbox in table header to toggle all inputs 
      .on('change', function() { 
       // prevent updateCell for every cell 
       $table[0].ignoreChange = true; 
       var c = this.checked, 
        col = $(this).closest('th').attr('data-column'); 
       doChecky(c, col); 
       // update main & sticky header 
       $table.add($sticky).find('th[data-column=' + col + '] input').prop('checked', c); 
       $table.children('tbody').children('tr:visible').toggleClass(highlightClass, c); 
       // update all at once 
       $table[0].ignoreChange = false; 
       $table.trigger('update', [ resort ]); 
      }) 
      .on('mouseup', function() { 
       return false; 
      }); 

    }); 
}); 

Należy również pamiętać, że gdy wywołanie ajax jest wykonywana, a zmiany zostały zastosowane, to znaczy, gdy „update” metoda powinna być wyzwalane, a nie „updateCell”.

Wreszcie istnieje istniejący input-select parser, ale nie zawiera metody zapobiegania masowym wywoływaniom metod updateCell w porównaniu do aktualizacji tabeli naraz.

0

Tabela sortowania jest doskonale pracuje na polach wejściowych, które są wprowadzoną przez użytkownika, ale pola tekstowe, które są wypełniane z bazy danych przy użyciu ajax nie sortuje się prawidłowo.

Dzieje się tak dlatego, że po załadowaniu strony, biblioteka jQuery & biblioteki stół sorter są ładowane w tym czasie i tabela sortowania funkcjonalność zostanie dodana do tabeli w tym czasie.

tablesorter-demo

Oto przykład ..

<script type="text/javascript" src="/path/to/jquery-latest.js"></script> 
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> 
$(document).ready(function() 
    { 
     $("#tablesorter-demo").tablesorter(); 
    } 
); 

A gdy zawartość są ładowane za pośrednictwem AJAX, tabela ta właściwość sortowania został już dodany do stołu & jest nie dotyczy nowych danych pobranych przez funkcję AJAX, ponieważ funkcja AJAX działała po początkowym załadowaniu strony. Więc wszystko, co musisz zrobić, to dodać tabelę sorter właściwości

$ ("# tablesorter-demo"). Tablesorter();

tuż nad linią

jQuery ("# tablesorter-demo") spustu ('updateCell.');

Mam nadzieję, że to pomoże .. ponieważ zadziałało dla mnie, gdy napotkałem ten sam problem podczas ładowania zawartości poprzez AJAX & próbując je sortować.

+0

Próbowałem tej poprawki przed, nawet teraz również, to nie działa dla mnie .. co jeszcze powinienem zrobić inorder, aby to naprawić? ten problem odżywił moje godziny pracy – prdp

+0

Jaki błąd pojawia się w konsoli podczas uruchamiania tej strony ??? @prdp –

+0

W tej chwili nie otrzymuję żadnego błędu, ponieważ nieaktywne pola wejściowe sortują idealnie, ponieważ wywołanie tablesorter jest w funkcji keyup. Ten, który działa, to wyłączone pola wejściowe w mojej tabeli, w których wartości są zapełniane przez AJAX, sortowanie nie działa, więc nie ma błędów w konsoli – prdp

0

Spróbuj tego ...

jQuery('.bulkupload').keyup(function() { 
    check = 1; 
    jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F"); 
    var part_no1 = jQuery("#" + jQuery(this).attr("id")).val(); 
    var fieldcount = part_no1.toString().length; 
    var thenum = jQuery(this).attr("id").replace(/^\D+/g, ''); 

    if (jQuery('#qty' + thenum).val() == '') { 
     jQuery('#qty' + thenum).val('Enter Quantity'); 
     jQuery('#qty' + thenum).css("color", "#DF1F26"); 
    } 

var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails"; 
    ajaxfunction(url1); 
    function ajaxfunction(url1) 
    { 

     if(window.XMLHttpRequest) 
     { 
      xmlhttp=new XMLHttpRequest(); 

     } 
     else 
     { 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.onreadystatechange=function()//callback fn 
     { 
      if(xmlhttp.readyState==4 && xmlhttp.status==200) 
      { 
       var response=xmlhttp.responseText; 
       if (response == "check") { 
        jQuery('#item_name' + thenum).val("Not Found"); 
        jQuery('#item_desc' + thenum).val("Not Found"); 
        jQuery('#av_qty' + thenum).css("color", "#DF1F26"); 
        jQuery('#item_name' + thenum).css("color", "#DF1F26"); 
        jQuery('#item_desc' + thenum).css("color", "#DF1F26"); 
        jQuery('#brand_name' + thenum).css("color", "#DF1F26"); 
       } 
       else { 
        var result1 = jQuery.parseJSON(response); 

        jQuery('#item_name' + thenum).val(result1.prodname1); 
        jQuery('#item_desc' + thenum).val(result1.productdescription1); 
        jQuery('#brand_name' + thenum).val(result1.brand); 
        jQuery('#av_qty' + thenum).css("color", "#DF1F26"); 
        jQuery('#item_name' + thenum).css("color", "#DF1F26"); 
        jQuery('#item_desc' + thenum).css("color", "#DF1F26"); 
        jQuery('#brand_name' + thenum).css("color", "#DF1F26"); 
        if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) { 
         jQuery('#av_qty' + thenum).val("Not in Stock"); 
        } else { 
         jQuery('#av_qty' + thenum).val(result1.stock); 
        } 

        jQuery("#tablesorter-demo").trigger('updateCell'); 
        $("#tablesorter-demo").tablesorter(); 
       } 



      } 
     } 

     xmlhttp.open("GET",url1,true); 
     xmlhttp.send(); 

    } 

}); 
+0

Tablesorter został już zainicjowany, gdy wywoływane jest wywołanie ajax, więc inicjowanie tablesortera ('$ (" # tablesorter-demo "). tablesorter();)) po raz drugi nie robi nic - właściwie, w oryginalnej wersji tablesortera, jeśli dobrze pamiętam, inicjowanie tabeli po raz drugi faktycznie ją zepsuje. – Mottie

Powiązane problemy