Deny ajax call in empty spaces of typeahead.js

I worked with typeahead.js and downloaded data using the BloodHound remote option.

Everthing works as expected, except that when I enter only spaces in the textbox typeahead still sends ajax call .

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

Here is my code. I tried using the prepare function, but 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>' }, }); 
+6
source share
3 answers

I would try adding a keyUp event to the text box for filtering:

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

This will fire after the second space, which should mitigate unwanted behavior if the field also does not specify spaces.

+4
source

The remote property has a prepare function, which you can use the handle to this change before calling the wire.

As an example:

 function createBloodHoundConfig(options) { return { datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Name'), queryTokenizer: Bloodhound.tokenizers.whitespace, identify: options.identify, sufficient: 8, remote: { url: options.url, prepare: function (query, settings) { settings.url = settings.url.replace("{q}", query.trim()); return settings; } }, }; } 

Please note that in this case you do not provide the wildcard property, since it effectively reduces the execution of the token replacement.

+2
source

Why not try it?

 prepare: function (query, settings) { var word = $.trim(query); if(word){ settings.url = "/search?q=" + word; return settings; } }, 
0
source

Source: https://habr.com/ru/post/1013384/


All Articles