Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter results with special characters using jQuery DataTables plugin?

I am using the jQuery DataTables plugin in my application, and many of my table rows and filters have special characters, specifically ampersands (&) in them. When I try to filter on these columns, all records disappear and it displays "no matching records found".

I have tried encoding (i.e. htmlspecialchars) and decoding (i.e. htmlspecialchars_decode) the strings before they are printed onto the page, but neither seems to be working.

Example: http://jsfiddle.net/gkdcZ/3/

Any ideas why this might be happening, and how I can fix it?

HTML:

<select id="filter_col_1" name="filter_col_1">
    <option value="">Select</option>
    <option value="A&B">A&B</option>
    <option value="C">C</option>
    <option value="D">D</option>   
</select>

<tr>
    <td>A&B</td>
    <td>Jones, Brandon</td>
    <td>01/02/2003</td>
</tr>

JavaScript:

$("#filter_col_1").change( function() { 
    $('#results').dataTable().fnFilter(
        '\\b' + $("#filter_col_1").val() + '\\b',
        1,
        true,
        false
    );
} );    

UPDATE #1: Issue appears to only happen when you limit the column. See DataTables API. Works fine when parameter is set to "null". http://jsfiddle.net/gkdcZ/4/

UPDATE #2: A bit closer. Adding in a function to replace HTML Entities works for certain characters (i.e. ampersands), but does not work for other characters (i.e. exclamation points and question marks). See http://jsfiddle.net/cz6Bs/4/

'\\b' + htmlEntities($('#filter_col_1').val()) + '\\b'

function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;')
                  .replace(/</g, '&lt;')
                  .replace(/>/g,     '&gt;')
                  .replace(/"/g, '&quot;');
}
like image 658
Michael Avatar asked Jan 22 '12 15:01

Michael


3 Answers

There is indeed a bug with dataTables that causes problems with any special chars so you'll have to escape them.

http://jsfiddle.net/cz6Bs/

Note: I added XRegExp as another resource for the escaping. http://xregexp.com/

like image 176
CashIsClay Avatar answered Nov 15 '22 23:11

CashIsClay


Try this one:

$(document).ready(function() { 
$('#results').dataTable();
$("#filter_col_1").change( function() { 
    $('#results').dataTable().fnFilter(  
'\\b' + htmlEntities($('#filter_col_1').val()) + '\\b', 
 0,
true,
false
);
 } );  


});    
function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g,     '&gt;').replace(/"/g, '&quot;');
}
like image 3
sm13294 Avatar answered Nov 15 '22 21:11

sm13294


try this

 $('#results').dataTable().fnFilter(
        $("#filter_col_1").val(),
        null,
        true
    );

set it to filter on all columns , works now...

like image 1
Daniel Avatar answered Nov 15 '22 21:11

Daniel