jQuery plugin DataTables: How to highlight the cur

2019-01-07 21:32发布

问题:

I have started using the DataTables plugin (v1.6.2) for jQuery(v1.4.2), and I would like to ask you if you know a settings or a plugin that allow me to highlight the text used in search textbox on the filtered rows.

Thank you in advance

回答1:

I would have to suggest the highlight plugin :)

I'm using this in about the same scenario right now, it's given me no issues thus far.

The usage is pretty simple:

$("#myTable").highlight($("#searchBox").val());

Just put the highlight CSS class in your stylesheet styles like you want and that's it:

.highlight { background-color: yellow }


回答2:

You can use this function by coping this content :

jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
    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
    if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
        for (var i in oSettings.aoPreSearchCols) {
            if (oSettings.aoPreSearchCols[i].sSearch) {
            searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
            }
        }
    }
    // 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]) {
            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
        if (aData[j]) {         
            // If there is a search string try to match
            if ((typeof sSregex !== 'undefined') && (sSregex)) {
                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;
};

inside :

dataTables.search-highlight.js

an call it like this example:

<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.search-highlight.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
       var oTable = $('#example').dataTable();
       oTable.fnSearchHighlighting();
    } );
</script>

and add this code to you css file:

.filterMatches{
    background-color: #BFFF00;
}


回答3:

I know that this question is now over 6 years old and the answers here may helped you at the time of asking. But for people still searching for this, there is a new plugin to integrate mark.js – a JavaScript keyword highlighter – into DataTables: datatables.mark.js.

Usage is as simple as:

$("table").DataTables({
    mark: true
});

Here is an example: https://jsfiddle.net/julmot/buh9h2r8/

This is the cleanest way and also gives you options none of the given solutions offers you.

There's now an official DataTables blog article available.



回答4:

You can use the following add on

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;
};

This solution is working for me. Note: Currently it does not support individual column filtering, but you just have to uncomment following in the code.

searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");

I have tested this with datatables 1.10.2 and jquery 1.9.2 version.



回答5:

This add on have better feature for highlighting search text. if you have created datatable in a dialog , then on dialog reopen you need to reinitialize datatable.

In DatatableHighlighter.js

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]) {
                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');
                //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);

            if (aData) {
                // If there is a search string try to match
                if ((typeof sSregex !== 'undefined') && (sSregex)) {
                    //For removing previous added <span class='filterMatches'>
                    var element = $(this);//convert string to JQuery element
                    element.find("span").each(function(index) {
                        var text = $(this).text();//get span content
                        $(this).replaceWith(text);//replace all span with just content
                    }).remove();
                    var newString = element.html();//get back new string

                    this.innerHTML = newString.replace( regex, function(matched) {

                        return "<span class='filterMatches'>"+matched+"</span>";
                    });
                }
                // Otherwise reset to a clean string
                else {
                    //For removing previous added <span class='filterMatches'>
                    var element = $(this);//convert string to JQuery element
                    element.find("span").each(function(index) {
                        var text = $(this).text();//get span content
                        $(this).replaceWith(text);//replace all span with just content
                    }).remove();
                    var newString = element.html();
                    this.innerHTML = newString;//$(this).html()//$(this).text();
                }
            }
        });
        return nRow;
    }, 'row-highlight');
    return this;
};

and call it like this ....

$("#button").click(function() {
                  dTable = $('#infoTable').dataTable({"bPaginate": false,"bInfo" : false,"bFilter": true,"bSort":false, "autoWidth": false,"destroy": true,
              "columnDefs": [
                               { "width": "35%", "targets": 0 },
                               { "width": "65%", "targets": 1 }
                             ]});
          $(".dataTables_filter input[type='search']").val('');
          $("span[class='filterMatches']").contents().unwrap();
          dTable.fnSearchHighlighting();
          $("span[class='filterMatches']").contents().unwrap();


        $("#AboutDialog").dialog('open');

    });