Require minimum filter input length with TomSelect (like select2's minimumInputLength)

608 views Asked by At

I have a webpage with a multi-select field for names, and to prevent biases, I want to only show list entries to users after they have entered at least 3 characters into the filter/search field.

Select2 supports this using the minimumInputLength setting (jsbin)

What would be the best way to achieve this with TomSelect? jsbin-template for tomselect here

Their documentation lists the shouldLoad setting as a possibility, with this explanation:

Use the shouldLoad() callback to implement minimum input length or other input validation. If the callback returns false, load() will not be called and the not_loading template will be added to the dropdown instead of the loading or no_results templates.

However, it seems that shouldLoad only limits whether load() will be called to fetch additional results from the remote resource, but any results that are already available will always be shown, no matter what shouldLoad returns (jsbin mre).

1

There are 1 answers

0
Tafa On

shouldLoad works, you have to return on callback when you satisfy with the query, load will only call the api if the return of shouldLoad is true shouldLoad? You can set minimun, regex, or any validation that you want.

new TomSelect("#your_select", {
    valueField: "id",
    labelField: "name",
    searchField: "name",
    shouldLoad: function (query, callback) {
        if (query.length > 3) {//if search has at least 4 chars
            return true;
        }
    },
    load: function (query, callback) {
        var url = "/your/url/remote/" + encodeURIComponent(query);
        fetch(url)
            .then((response) => response.json())
            .then((json) => {
                callback(json);
            })
            .catch(() => {
                callback();
            });
    },
});

For remove your previous results, you can use clear() to clear selected and removeItem before each load.