Select2 ignore certain input?
Asked Answered
B

2

7

So I'm using the Select2 JQuery based replacement for select boxes.

I've set it up (with help from an example I found) for remote data searching via ajax which works great. I've got a minimum input value of 3 so the user has to enter at least 3 characters before the search starts (otherwise "A" would return 90% of the searchable values).

Unfortunately a large portion of my searchable values also start with "The". So if a user types "The", 50% of the results get returned, populating a huge dropdown with basically unfiltered results ... not ideal!

Is there any way to get Select2 to ignore certain set phrases, ie typing "The" shouldn't count towards the minimum 3 character count!

$('#searchInput').select2({
    minimumInputLength: 3,
    placeholder: 'Please search here ...',
    ajax: {
        url: "/api/v1/institutes",
        dataType: 'json',
        quietMillis: 100,
        data: function(term, page) {
            return {
                query: term
            };
        },
        results: function(data, page ) {
            return { results: data }
        }
    },
    formatResult: function(institute) { 
        return "<div class='select2-user-result'>" + institute.name + "</div>"; 
    },
    formatSelection: function(institute) { 
        return institute.name; 
    },
    initSelection : function (element, callback) {
        var elementText = $(element).attr('data-init-text');
        callback({"term":elementText});
    }
});
Brighton answered 20/5, 2014 at 16:23 Comment(4)
Not sure if select2 has the API for that, though another way to come at this issue is to modify your API server process (if possible) to not do searches for "the" or "the " and only once they type the 4/5th letter, then return a result. In the meantime you could return 'Too broad a search term' for people that just type 'the' or any other word you identify.Falzetta
Looking at the docs: ivaynberg.github.io/select2 it looks like you can replace ajax: with query: for your own custom function where you have to code the ajax yourself but it means you can add in any custom checks.Falzetta
what does your /api/v1/institutes look like? Couldn't you just create a filter to ignore The in there before it query's your table?Whitaker
oh wow I just realized this was from 2014 lolWhitaker
B
0

You can check Select2 docs - search, where you can customize to match your pattern.

Beryllium answered 26/6, 2019 at 20:52 Comment(0)
P
0

I faced the same problem. I solved the problem by using "data-minimum-input-length" attribute in html code.

<select id="mySelect" data-minimum-input-length="3"></select>
Polk answered 7/2, 2022 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.