Marc Rasmussen
Marc Rasmussen

Reputation: 20555

select2 search pressing space selects the item

I have the following select2:

Now as soon as I press space it automatically selects the thing I've written (which means I can't search for items with space)

Here is my javascript:

let term;
$('.js-data-example-ajax').select2({
  tags: true,
  multiple: false,
  tokenSeparators: [',', ' '],
  minimumInputLength: 2,
  minimumResultsForSearch: 10,
  ajax: {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + btoa(environment.CVRTOKEN + ':' + '')
    },
    data: function(params) {
      term = params.term;
      this.queryParam = params.term;
      return params;
    }.bind(this),
    url: function() {
      return 'https://rest.cvrapi.dk/v1/dk/suggestions/company/' + $('.select2-search__field').val();
    },
    dataType: 'json',
    type: 'GET',
    processResults: function(data) {
      return {
        results: $.map(data, function(item) {
          return {
            text: item.life.name,
            id: item.vat
          };
        })
      };
    }
  }
});

And my simple HTML:

<div class="form-group">
  <label>Firma</label>
  <select class="js-data-example-ajax form-control" style="height: 38px"></select>
</div>

Can anyone tell me why this is happening?

Upvotes: 1

Views: 797

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

Since you have used:

tokenSeparators: [',', ' '],

The second separator is a space character. So when you press Space, that considers it as a token. You have to change to code to tell that you are not going to separate tokens by space.

tokenSeparators: [','],

Upvotes: 2

Related Questions