datatables 1.10 - search highlight on sAjaxSource JSON data

datatables 1.10 - search highlight on sAjaxSource JSON data

sreenu539sreenu539 Posts: 10Questions: 2Answers: 0
edited August 2014 in Free community support

Hello Datatablers,

I am trying to implement search highlight on data table ( JSON data is coming and filling up the table from serverside through "sAjaxSource"), Please see the below code for details.

search is working by default, BUT highlight is not working at all.

I alerted data of searchTxt+=$('#search_input').val(); alert("txt" + searchTxt);
and alert is displaying search input box text.

Alert for " alert(""+ aData[j]); " displaying "undefined rather than column data and highlight is not working.

Could anyone shed some light on this ?

Thank you,
Sri


<script> jQuery(document).ready(function() { var oTable = jQuery('#example').dataTable({ "sDom": '<"#table_header"<"#inner_table_header"<"filtertx">fCT<"filterbtn">>>tipl', "sAjaxSource": ajaxURL, "bDeferRender": true, "bProcessing" : true, "bJQueryUI": true, "sScrollY": 500, "aaSorting": [[0, 'desc']], "aoColumns": [ { "mData": "name" }, { "mData": "flag" } ], "oSearch": {"sSearch": "", "bSmart": true, "bRegex": false}, "sPaginationType": "paginate", "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { $(nRow).addClass('clickable'); $(nRow).attr('onClick', "editPopup(" + aData['conditionId'] + ")"); }, "fnDrawCallback": function( oSettings ) { $(expandWrapper); } }); $("#example_filter label").attr("for", "search_input"); $("#example_filter input").attr({ "id": "search_input", "placeholder" : 'search' }); oTable.fnSearchHighlighting(); }); jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) { // Initialize regex cache oSettings.oPreviousSearch.oSearchCaches = {}; oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) { // Initialize search string array var searchStrings = []; var oApi = this.oApi; var cache = oSettings.oPreviousSearch.oSearchCaches; // Global search string // If there is a global search string, add it to the search string array if (oSettings.oPreviousSearch.sSearch) { searchStrings.push(oSettings.oPreviousSearch.sSearch); } // Individual column search option object // If there are individual column search strings, add them to the search string array searchTxt=$('#filter_input input[type="text"]').val(); searchTxt+=$('#search_input').val(); alert("txt" + searchTxt); if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) { for (var i in oSettings.aoPreSearchCols) { if (oSettings.aoPreSearchCols[i].sSearch) { searchStrings.push(searchTxt); } } } // Create the regex built from one or more search string and cache as necessary if (searchStrings.length > 0) { var sSregex = searchStrings.join("|"); if (!cache[sSregex]) { // This regex will avoid in HTML matches cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i'); } var regex = cache[sSregex]; } // Loop through the rows/fields for matches jQuery('td', nRow).each( function(i) { // Take into account that ColVis may be in use var j = oApi._fnVisibleToColumnIndex( oSettings,i); // Only try to highlight if the cell is not empty or null alert(""+ aData[j]); if (aData[j]) { // If there is a search string try to match if ((typeof sSregex !== 'undefined') && (sSregex)) { alert("here"); this.innerHTML = aData[j].replace( regex, function(matched) { return "<span class='filterMatches'>"+matched+"</span>"; }); } // Otherwise reset to a clean string else { this.innerHTML = aData[j]; } } }); return nRow; }, 'row-highlight'); return this; }; </script>

Answers

  • sreenu539sreenu539 Posts: 10Questions: 2Answers: 0

    I am using mData, sAjaxSource to populate data in datatable.

    the following closure having an issue

    jQuery('td', nRow).each( function(i) { ...aData[j] ...}

    aData[j] is undefined, I am really not sure, how to get this datatable cell data which rendered by mData .

    I appreciate any kind of help on this.

    Thanks,
    Sri

  • shantanooshantanoo Posts: 2Questions: 1Answers: 0

    Hi so I looked at your code did some modifications. and it is working for me below is the modified code.

    jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
    // Initialize regex cache
    oSettings.oPreviousSearch.oSearchCaches = {};

        oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            // Initialize search string array
            var searchStrings = [];
            var oApi = this.oApi;
            var cache = oSettings.oPreviousSearch.oSearchCaches;
            // Global search string
            // If there is a global search string, add it to the search string array
            if (oSettings.oPreviousSearch.sSearch) {
                searchStrings.push(oSettings.oPreviousSearch.sSearch);
            }
            // Individual column search option object
            // If there are individual column search strings, add them to the search string array
    
         //   searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
            var searchTxt = $('input[type="search"]').val();
            // console.log("txt" + searchTxt);
            if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
                for (var i in oSettings.aoPreSearchCols) {
                    if (oSettings.aoPreSearchCols[i].sSearch) {
                    searchStrings.push(searchTxt);
                    }
                }
            }
            // Create the regex built from one or more search string and cache as necessary
            /*if (searchStrings.length > 0) {
                var sSregex = searchStrings.join("|");
                if (!cache[sSregex]) {
                    // This regex will avoid in HTML matches
                    cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
                }
                var regex = cache[sSregex];
            }*/
            if (searchStrings.length > 0) {
                var sSregex = searchStrings.join("|");
                if (!cache[sSregex]) {
                    var regRules = "("
                    ,   regRulesSplit = sSregex.split(' ');
    
                    regRules += "("+ sSregex +")";
                    for(var i=0; i<regRulesSplit.length; i++) {
                      regRules += "|("+ regRulesSplit[i] +")";
                    }
                    regRules += ")";
    
                    // This regex will avoid in HTML matches
                    cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
                }
                var regex = cache[sSregex];
            }
    
            // Loop through the rows/fields for matches
            jQuery('td', nRow).each( function(i) {
    
                // Take into account that ColVis may be in use
                var j = oApi._fnVisibleToColumnIndex( oSettings,i);
                // Only try to highlight if the cell is not empty or null
             //   console.log("data "+ aData[j] + " j " + j);
             //   console.log("data 1  "+ nRow);
                if (aData) {
                    // If there is a search string try to match
                    if ((typeof sSregex !== 'undefined') && (sSregex)) {
                        //console.log("here :: "+$(this).text());
                        this.innerHTML = $(this).text().replace( regex, function(matched) {
    
                            return "<span class='filterMatches'>"+matched+"</span>";
                        });
                    }
                    // Otherwise reset to a clean string
                    else {
                        this.innerHTML = $(this).text();//aData[j];
                    }
                }
            });
            return nRow;
        }, 'row-highlight');
        return this;
    };
    

    Highlight of changes

    1. Instead of using aData[j] i.e. visible column index I used aData only, because not always your data will be an array, it might also be in object :)
    2. insead of using aData[j] for replacing I am actually using $(td).text()
    3. Also your script was throwing error as searchText was not defined so I had to define that.

    Try using this code and let me know

  • brainformatikbrainformatik Posts: 6Questions: 0Answers: 0
    edited January 2015

    Hi,
    i'm new to datatables and I use almost the same functionality to highlight search results.

    Has anyone tried this plugin with colReorder extension?

    I use server side processing to get data and stateSave = true.

    Highlighting works until a column is dragged to another position.
    On load of first page, highlighting doesn't work. Every other action after initial load works (filtering, sorting, page change) and filter string is highlighted.

    Could it be that for initial load (first page) highlighting is done in e.g. a hidden array (cache or temp data of colReorder)?

    Another behaviour I have recognized is that colums for first page load are in original order, every other action sends the columns in colReorder order ;-)

    Hope I could explain where the problem is and hope that somebody can help me.

    Edit: It seems to be a problem connected with stateSave, I disabled server side processing and colReorder for further tests. Every time I reload the page, highlighting disappears.

This discussion has been closed.