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, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
There is indeed a bug with dataTables that causes problems with any special chars so you'll have to escape them.
Note: I added XRegExp as another resource for the escaping. http://xregexp.com/