Guide on using Twitter Typeahead.js to capture all matching elements in a specific string

When using twitter typeahead.js, it typically returns elements that match only at the beginning of a string. For example:

source: ['type','typeahead','ahead']

query: 'type'

Returns: 'type' and 'typeahead'

--

query: 'ahead'

Returns: 'ahead'

However, I would like it to also return 'ahead' and 'typeahead'

This is the code I have written for it:

var clients = new Bloodhound({
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: '/clients.json',
        filter: function(list) {
            return $.map(list, function(value) { return { name: value }; });
        }
    }
});

clients.initialize();

$('.client').typeahead(null, {
    displayKey: 'value',
    source: clients.ttAdapter(),
    minLength: 1,
});

I have found a similar question regarding this issue, but the answer provided was difficult for me to understand.

Answer №1

I managed to solve the issue by realizing that my familiarity with bootstrap2 typeahead was hindering my understanding of the datumTokenizer. For those who may be struggling to grasp it, here is a brief explanation:

queryTokenizer: This is an array of words that you are searching for. For example, if you search for 'test abcd', it will break down the string into ['test','abcd'] and then identify matches based on these words.

datumTokenizer: This is an array of words that will be compared with the queryTokenizer. Each JSON item will have its own set of words to compare against.

For instance, if you have a data source like:

['good test','bad test']

and you search for 'est', your datumTokenizer should return an array containing 'est'. Here's how it could look:

['good','test','ood','od','test', 'est', 'st'] for the first item

['bad','ad','test', 'est', 'st'] for the second item

Below is the code I came up with. It may not be the most efficient solution, but I believe it can still be helpful:

new Bloodhound({
    datumTokenizer: function(d) {
        var test = Bloodhound.tokenizers.whitespace(d.value);
            $.each(test,function(k,v){
                i = 0;
                while( (i+1) < v.length ){
                    test.push(v.substr(i,v.length));
                    i++;
                }
            })
            return test;
        },
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    limit: 10,
    prefetch: {
        url: '/lista.json',
        ttl: 10000
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When implementing the Dropdown Picker, it is important to avoid nesting VirtualizedLists inside plain ScrollViews for optimal

Currently, I am utilizing the RN library react-native-dropdown-picker. However, when I enclose this component within a ScrollView, it triggers a warning: "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because ...

Expand the clickable area of the checkbox

Is it possible to make clicking on an empty space inside a table column (td) with checkboxes in it check or uncheck the checkbox? I am limited to using only that specific td, and cannot set event handlers to the surrounding tr or other tds. The functional ...

Finding the text within a textarea using jQuery

My journey with jQuery has just begun, and following a few tutorials has made me feel somewhat proficient in using it. I had this cool idea to create a 'console' on my webpage where users can press the ` key (similar to FPS games) to send Ajax re ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

sequentially animating elements using animate css in a choreographed manner

I have created a unique jsfiddle with 20 boxes that I am trying to animate using the Animate.css plugin. The plugin can be found at daneden.me/animate. My goal is to animate each box one after the other in a sequential manner, but I seem to be having trou ...

Issue encountered while attempting to set up react-native project

Whenever I attempt to create a new react-native project using the command: npx react-native init myproject I encounter the following errors: ERESOLVE is overriding peer dependency npm gives me a warning while trying to resolve: [email protected] ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Is it possible to incorporate async await with SetState in React?

Is there a way to properly setState when needing async/await data inside it? I know it's not recommended, but I'm struggling with getting data before setting the state. Any suggestions? codesanbox: https://codesandbox.io/s/infallible-mendeleev-6 ...

Storing the result of parsing JSON data into a global variable

$(function() { var countFromData = 0; getReminder(); alert(countFromData); }); function getReminder() { $.getJSON("<?=base_url()?>home/leavereminder", {}, function(data) { ...

The code functions properly within the emulator, however, it fails to execute on an actual device

Yesterday, I posted a question about the background related to this topic: on click event inside pageinit only works after page refresh. I received an answer for my question and tested it in Chrome devtools where it worked perfectly. However, today when ...

JavaScript interval setting multiples

In my current situation, I have implemented a setInterval based code that continuously checks the value of an AJAX call response. Here is how it looks: var processInterval = setInterval(function () { var processResult = getVideoStatus(data.file_name) ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

Having trouble resolving this issue: Receiving a Javascript error stating that a comma was expected

I am encountering an issue with my array.map() function and I'm struggling to identify the problem const Websiteviewer = ({ web, content, styles, design }) => { const test = ['1' , '2'] return ( {test.map(item => { ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

The search for the view in the directory "/views" was unsuccessful in Express 4.0

I've been working on a project using Express 4.0 and the Express3-handlebars libraries for NodeJS. Below is the setup: app.set('views', path.join(__dirname, 'views/')); app.engine('hbs', hbs({defaultLayout: 'main&a ...

Having issues with my toggler functionality. I attempted to place the JavaScript CDN both at the top and bottom of the code, but unfortunately, it is still not

I recently attempted to place the JavaScript CDN at the top of my code, but unfortunately, it did not have the desired effect. My intention was to make the navigation bar on my website responsive and I utilized a toggler in the process. While the navbar di ...