Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ajax call on empty spaces typeahead.js

I have been working with typeahead.js and loading data using BloodHound remote option.

Everthing is working as expected except that when i enter only spaces in textbox typeahead still sends ajax call.

I want to know if there is way to prevent ajax call if there are only spaces in textbox. I am looking for similar behavior like trim.

Here is my code. I have tried to use prepare function but with no luck.

var dataSource = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('ProductID', 'ProductName'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
              url: urlVar + "LoadAllProductByProductName/%QUERY",
              wildcard: '%QUERY',

            },
    sufficient: 3,
   });

const $tagsInput = $('.txtProductName')
$tagsInput.typeahead({
   minLength: 3,
   source: dataSource,
   hint: false,
   highlight: true,
   isBlankString: false
   },
   {
      limit: 10,
      source: dataSource,
      name: 'dataSource',
      display: function (item) {
         return item.ProductName
      },
      suggestion: function (data) {
         return '<div>' + data.ProductName + '–' + data.ProductID + '</div>'
      },

});
like image 378
Mairaj Ahmad Avatar asked Dec 21 '16 11:12

Mairaj Ahmad


1 Answers

I would try attaching a keyUp event to the text box to perform the filtration:

$tagsInput.keyup(function(){
        this.value = this.value.replace(/  */, ' ');
    });

That will fire after the second space, which should mitigate the undesired behavior unless there are non-space characters in the field, as well.

like image 154
sorak Avatar answered Oct 21 '22 15:10

sorak