Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ignore HTML when filtering a jQuery data table?

I'm using the jQuery DataTables plugin, and having a slight problem with the filtering feature in it. If I have a table cell with content like <a href='foo6'>Blah</a>, and I filter for "6", that cell will show up, even though there is no "6" in "Blah". What I'd like to do is have the DataTables plug-in ignore HTML when doing it's filtering.

I've tried scouring the DataTables site, and found conflicting, un-helpful leads. One post suggested that I needed an sType:'html' option in the definition of my aaColumns, but I tried that and it didn't help ... plus a later post suggested that the current version of DataTables auto-detects the HTML sType. I also found this code snippet:

// Make filtering ignore HTML (see http://datatables.net/plug-ins/filtering)
$.fn.dataTableExt.ofnSearch['html'] = function ( sData ) {
    var n = document.createElement('div');
    n.innerHTML = sData;
    if (n.textContent) {
        return n.textContent.replace(/\n/g," ");
    } else {
        return n.innerText.replace(/\n/g," ");
    }
};

which was supposed to fix things ... but it didn't.

So, my question is: does anyone out there know how to make DataTables ignore non-text (ie. HTML) content when filtering rows?

like image 239
machineghost Avatar asked Sep 20 '12 17:09

machineghost


1 Answers

It turned out I needed a custom mRender function on my column headers. More importantly (since I had tried this at first without checking the "type" argument) you need to use the type argument provided to that function to make it only apply when filtering.

My end result looked something like this:

aaHeaders: [{
    mRender: function(data, type, full) {
        // If we're filtering, don't look at the HTML; only filter on the text
        return type == 'filter' ? $(data).text() : data
    }
}], //...
like image 111
machineghost Avatar answered Sep 23 '22 03:09

machineghost