Im using jquery Tokeninput library for autocomplete functionality. Im currently struggling with the issue I have with the search results. When I type something, it returns all the words for characters which are being typed. I want it to only return the search results where initial strings match.
For example, if I type "Na", it returns all the words which have "Na" such as "Canada", "Financial" etc.
I would ONLY like for it to return words which start with "Na" such as "Nation", "Nascar" etc.
Im new to JavaScript to facing trouble updating this script. Can someone please help ?
Here is the library that Im using - https://github.com/loopj/jquery-tokeninput/blob/master/src/jquery.tokeninput.js
$("#demo-input").tokenInput([
{id: 7, name: "Canada"},
{id: 11, name: "Financial "},
{id: 13, name: "Nation"},
{id: 17, name: "Nascar"},
{id: 19, name: "USA"},
{id: 31, name: "Economics"}
]);
I checked library code and I don't think you can pass any option to change default search type which checks for existence of search query within a value. However, I found a heck which you could use (IMO you shouldn't unless necessary).
Working example here
Library allows you to process search results by using onResult
and onCachedResult
callbacks you could use that for your leverage.
$("#demo-input").tokenInput([
{id: 7, name: "Canada"},
{id: 11, name: "Financial "},
{id: 13, name: "Nation"},
{id: 17, name: "Nascar"},
{id: 19, name: "USA"},
{id: 31, name: "Economics"}
],
{
onResult: filterSearchResults,
onCachedResult: filterSearchResults
});
function filterSearchResults(items){
var query = $("#demo-input").parent().find("ul li input").val().toLowerCase();
return items.filter(i => i.name.toLowerCase().startsWith(query));
}