What is the best way to display items using Typeahead.js in combination with the Bloodhound engine?

I am struggling to showcase a collection of items using typeahead with a JSON file as the data source. Unfortunately, none of my information is appearing on the screen.

My objective is to list the names and utilize the other attributes for different purposes once selected.

../data/test.json

[   
    {"name": "John Snow", "id": 1},
    {"name": "Joe Biden", "id": 2},
    {"name": "Bob Marley", "id": 3},
    {"name": "Anne Hathaway", "id": 4},
    {"name": "Jacob deGrom", "id": 5}
]

test.js

$(document).ready(function() {
    var names = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace("name"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
          url: '../data/test.json'
        }
    });
    names.initialize();

    $('#test .typeahead').typeahead({
        name: 'names',
        displayKey: 'name',
        source: names.ttAdapter()
    });
)};

test.html

<div id="test">
    <input class="typeahead" type="text">
</div>

** If someone could provide me with an explanation of what the datumTokenizer and queryTokenizer are, that would be greatly appreciated **

Answer №1

The JSON file includes a series of JSON objects, but the Bloodhound suggestion engine requires an array of JavaScript objects.

Therefore, it is necessary to apply a filter to your prefetch declaration:

prefetch: {
 url: '../data/test.json',
 filter: function(names) {
   return $.map(names, function(name) { 
    return { name: name };
 });
}

Regarding the "datumTokenizer," its purpose is to define how the datums (suggestion values) should be tokenized. These tokens are then utilized to match with the input query.

For example:

Bloodhound.tokenizers.whitespace("name")

This function takes a datum (in this case, a name value) and splits it into two tokens, such as "Bob Marley" being split into "Bob" and "Marley".

You can observe how the whitespace tokenizer functions by examining the typeahead source:

function whitespace(str) {
 str = _.toStr(str);
 return str ? str.split(/\s+/) : [];
}

Notice how it separates the datums using the regular expression for whitespace (\s+ meaning one or more white space characters).

In the same way, the "queryTokenizer" also dictates how to tokenize the search term. In your case, you are utilizing the whitespace tokenizer, so a search term like "Bob Marley" will generate datums "Bob" and "Marley".

Therefore, with these tokens established, if you were to search for "Marley," a match would be found with "Bob Marley."

Answer №2

Here's a simpler solution for you. Everything you've done so far is correct, but there's just one small mistake. You can actually use an object array as demonstrated in your code.

Just replace displayKey: 'name' with display: 'name' and it should work perfectly.

Therefore, the complete typeahead function will appear like this:

$('#test .typeahead').typeahead({
    name: 'names',
    display: 'name',
    source: names.ttAdapter()
});

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

Design a webpage using material-ui components

I'm struggling to create a layout using material-ui for a child page. Can someone guide me on how to achieve this design? https://i.sstatic.net/TwYR5.png ...

Capturing Exceeding JSON Length Limit in ASP.NET MVC Serialization

I encountered an issue when trying to return a large JSON result: The string length exceeds the maxJsonLength property value set. I attempted to catch the exception during serialization, but it doesn't work as expected. try ...

Transferring information among components and incorporating the ngDoCheck function

We are currently working on transferring data from one component to another using the following method. If there is no data available, we display an error message; however, if there is data present, we populate it in a select box. showGlobalError = true; ...

Having difficulty implementing DragControls

My experience with three.js is at a beginner level, and I recently attempted to incorporate a feature allowing the dragging of a 3D model. During this process, I encountered DragControl but faced difficulty implementing it in my code. Upon using new DragCo ...

Unraveling the Mysteries of AngularJS in a Tutorial Snippet

After reading through the enlightening theory snippets in Step 3 of AngularJS Tutorial, one particular passage piqued my curiosity: The scope, which connects our controller and template to create a dynamic view, is not isolated within its own bounda ...

How can I prevent clicks on child links using the :not() selector?

I am working on a script using JQuery where I want to add a click handler to a div while ignoring clicks on the children a tags within it. You can check out my attempt (which is not working as expected) on this JSFiddle link: http://jsfiddle.net/q15s25Lx/ ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

Utilize the click spinner feature on a single button in Angular

I have a table with a list of items and each item has a button to request a PDF document from the server. I want to show a spinner while waiting for the document to be received. Currently, when I click on a button, the spinner appears on all buttons instea ...

JavaScript compilation failure: Unhandled SyntaxError: Unforeseen token '>' in string variable within an if statement -- Snowflake

Looks like there's an issue with JavaScript compilation. The error message reads: Uncaught SyntaxError: Unexpected token '>' in HP_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. Strange how SF is not a ...

The Angular frontend appears to be experiencing difficulties displaying content on the website

I'm currently working through the AngularJS on Rails tutorial from Thinkster(). Check out my progress so far https://jsfiddle.net/dcbavw4e/ I'm not seeing anything on the web page. I've already installed node.js and npm. Are there any othe ...

Dealing with blank values in jQuery DataTables

I am currently utilizing jQuery DataTable to display data in table format; within the table, there is a button that triggers a Bootstrap Modal for editing two of these values, and I utilize Ajax to send the modified values to a Spring Controller. The init ...

Leverage the power of Angular's route resolve function

Can anyone assist me with a problem I'm facing? I am looking for a way to delay the display of a view until my data is loaded. After some research, I was thinking of using a resolve in the route, but I can't seem to figure out how to implement it ...

The Vue and Element popover feature is unable to modify the current page

After hiding the popover and reopening it, it seems that the value of currentPage remains unchanged. Below is the HTML CODE: <el-popover placement="bottom" trigger="click" title="网段详情" @hide="popoverHide"> <el-table :data="in ...

What could be causing this issue with my Mongoose.js program when it freezes during a 'nested' save operation?

[edit]: I made a revision to the previous question, providing a very precise reproducible example. This is the program I've created. I have developed two Schemas named ASchema and BSchema with collections A and B respectively. Then, I generated ...

Having difficulties understanding JSON and JSONP

I'm completely new to working with JSON and I am really struggling with making a cross-domain request. It's getting frustrating for me :( This is the code I currently have: $.getJSON('http://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0 ...

Implementing auto-suggest functionality in a React-Bootstrap Select component

I am seeking to create a specialized react select component that can search through a constantly updating list pulled from a server api in JSON format. I am currently exploring other options aside from React-select because it is not compatible with my proj ...

Words of wisdom shared on social media

How can I share text from my HTML page on Twitter? This is the code snippet from my HTML page - function change() { quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"]; auth = ["Raj", "Mogambo", "Gabbar"]; min = 0; max = ...

Encountering an issue with TS / yarn where an exported const object cannot be utilized in a consuming

I am currently working on a private project using TypeScript and Yarn. In this project, I have developed a package that is meant to be utilized by one or more other applications. However, as I started to work on the consumer application, I encountered an ...

Why does i18next only function on http://localhost:3000/de (landing page) in NextJS and not on http://localhost:3000/de/about?

I'm new to this and feeling lost on how to tackle this issue. I tried following the instructions on https://github.com/i18next/next-i18next, but I'm struggling with index.js. When I toggle /de on my landing page, it translates correctly in the UR ...