Adam
Adam

Reputation: 29079

Select2: Trim input whitespace

I am using Select2

<script type="text/javascript">
$(document).ready(function() {
  $(".select2").select2();
});
</script>

<select class="select2">
  <option>Anna</option>
  <option>Bob Hunter</option>
</select>

I want to find Anna when I search for Anna even if there are whitespaces before or after the name. If possible, I would even like to reduce multiple whitespaces always to one, such that Bob Hunter would find Bob Hunter. Is something like this possible? I couln't find anything like that in the options docs.

Upvotes: 1

Views: 2317

Answers (1)

Brijpal Singh
Brijpal Singh

Reputation: 56

You can use below code to trim whitespace at the beginning & end

    jQuery(element).select2({
        matcher: function (params, data) {
        // If there are no search terms, return all of the data
        if (jQuery.trim(params.term) === '') {
            return data;
        }
        var myTerm = jQuery.trim(params.term);
        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        if (data.text.toLowerCase().indexOf(myTerm.toLowerCase()) > -1) {
            // You can return modified objects from here
            // This includes matching the `children` how you want in nested data sets
            return data;
        }

        // Return `null` if the term should not be displayed
        return null;
        }
    });

Upvotes: 4

Related Questions