Skip to content

Implementing Ajax search filtering

yanickrochon edited this page Jan 9, 2013 · 1 revision

<<< Back to How to...

Since the behaviour of an Ajax search (or dynamic list search) is too abstract, it is not part of the widget's core functionality. However, implementing an Ajax feature is made easy thanks to the search event. The following code illustrates how this can be easily achieved, and could be modified to use a cache, etc.

####See a working demo here

$('#multiselect_test').bind('multiselectSearch', function(evt, ui) {
    // by default, clear out all results
    $(this).find('option:not(:selected)').remove().end().multiselect('refresh');
    // test that we only have valid characters to search...
    if (/^[0-9a-z\s]+$/i.test(ui.text)) {
        $.getJSON('dict_api.php', {q:ui.text})
            .always(function(json, s) {
                if (s === 'success') {
                    $.each(json, function() {
                        addOption(this);
                    });
                    $('#multiselect_test').multiselect('refresh');
                }
            });
    } else {
        // remove all unselected options and refresh
        evt.preventDefault(); // cancel search
    }
});