batz batz - 21 days ago 6
jQuery Question

jQuery dataTables search - Set search filter to get only matches that starts like search value

If you search in data tables a word, it will found anywhere in a word.

Example: Search of "b" in table:

banana
subway
sub


Will return all 3.

How could i set to get only "banana" if i type "b" in search field.

Answer

I dare to assume you are thinking about jQuery dataTables (have replaced the ambigious tag with the correct tag too).

You can create a custom filtering function if you want to filter on what the column data begins with, and not search / filter on the entire strings. Like this, which also is case insensitive :

$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        //$('#example_filter input') is the default #example filter box
        var term = $('#example_filter input')
                .val()
                .toLowerCase();

        for (var i=0;i<data.length;i++) {
            value = data[i]
                .toString()
                .toLowerCase();

            if (value.indexOf(term)==0) {
                return true;
            }
        };
        return false;
    }
);

see demo -> http://jsfiddle.net/v1yguqLz/

Note : This should per the documention and how dataTables worked in "the old days" be a task for a regular expression search, but I cannot get even the simpliest regular expression example to work, neither by table.search() nor table.column().search(). Have tried with 1.10.0 through to 1.10.5 (recent version). I guess this has something to do with this bugreport -> https://github.com/DataTables/DataTables/issues/341 and backwards compability.

On the other hand, if you just want to filter on what the column data begins with, then a custom filtering function is the perfect solution anyway.