Obtain the identification number and full name from the typeahead feature

I am able to retrieve the name and ID, but I am only able to display the name.

I have attempted using update and afterslected methods.

Currently, I have this code which works well, however, it only fetches the name!

 $('input.typeahead').typeahead({
    source:  function (query, process) {
    return $.ajax({
    url: "search/autocomplete",
    type: "GET",
    data: "query=" + query,
    success: function(data) {

      var data = $.merge( $.merge( [], data['2'] ), data['1'] );
      return process(data); 
    }
    });

   }         
 });

The expected outcome is to fetch both the name and the ID (the ID should be displayed in a separate div like #mydiv).

Thank you in advance!

Answer №1

To find the solution, you need to include the afterSelect function.

  $('input.typeahead').typeahead({
   source:  function (query, process) {
     return $.ajax({
     url: "search/autocomplete",
     type: "GET",
     data: "query=" + query,
     success: function(data) {

    var data = $.merge( $.merge( [], data['2'] ), data['1'] );

    return process(data); 

         // an array will be returned and can be checked with console
  }

});

},
 afterSelect: function(data){
    console.log(data.id);
}
 });

Answer №2

If you want to implement a typeahead directive using Bloodhound, follow these steps:

app.directive('typeheadDirective', function() {
    return {
        restrict: 'A',
        scope: {
            themes: '=',
            output: '=',
        },
        link: function(scope, element, attrs) {
            var themes = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('theme_name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: scope.themes,
            })
            element.typeahead(null, {
                name: 'themes',
                displayKey: function(item) {
                    return item.theme_name
                },
                source: themes.ttAdapter()
            })
            element.bind('typeahead:select', function(ev, theme) {
                scope.output = {
                    'id': theme.id,
                    /*'theme_id': theme.id,*/
                    'theme_name': theme.theme_name
                }
                // element.value = ''
                scope.$apply();
            })
        }
    };
});

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

How can I attach an event listener to an element that is added dynamically with jQuery?

I added a new div element dynamically using jQuery's on method. However, I'm having trouble getting a listener to work for the newly created element. HTML <input class="123" type="button" value="button" /> <input class="123" type="butt ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...

Accessing factory in controller using AngularJS

Currently, I am utilizing the following link to integrate requirejs with angularjs: https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 My question is regarding how to use a service function that is defined ...

Express JS is experiencing difficulties with the functionality of the iframe

When I'm using iframe in HTML, it works perfectly fine: <iframe src="main.html" height="100px"></iframe> But when I use Iframe in Express, it shows an error: <iframe src="main.html" height="100px&qu ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

Tips for resolving an issue with an array and the find method?

Seeking guidance on using the find method. Specifically, I am tasked with searching an array to find a specific string match. The catch is that this string may be nested within one of the objects in its child array. I attempted to create an if statement in ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Using Jquery to preserve the selected value in a radio button

Having two radio buttons, <div class="class1"> <span><input name="chk1" type="radio" checked="checked" id="check1"/>Option 1</span> <span><input name="chk2" type="radio" id="check2"/>Option 2</span> </div> ...

Maximizing the potential of Ajax for html() calls within D3.js: a comprehensive guide

After modifying some d3.js code to load content on the page, I encountered an issue with a specific part of the code not loading as expected. My goal is to use the D3.js .html() method instead of relying on the ajax call method, which involves variables an ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Format the image to fit within a div container

I'm currently utilizing Bootstrap and am looking to insert some images into my div while ensuring they are all the same size (standardized). If the images are too large (as they typically are), I want to resize them to fit within my div and crop them ...

Using Node.js to retrieve a p12 certificate from the certificate repository

Is there a way to retrieve the p12 certificate from the certificate store after it has been installed? I am facing a situation where both the private key and certificate are combined in a p12 certificate and then stored in the Windows certificate store. ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

Is there a way to retrieve the Response object in Express from outside the Route

Currently, my backend API is built using Express JS. Instead of using the res object directly in the route controller, I am looking to access it from a custom service. While I know that I can simply pass res as an argument to the service function and use ...

Ways to declare a function within the events onMouseOver and onMouseOut

<div align="right" style="border:1 #FF0 solid; background-color:#999" onMouseOver="javascript: function(){this.style.backgroundColor = '#DDD';}" onMouseOut="javascript: function(){this.style.backgroundColor = '#999';}"> Register & ...

Can someone help me figure out the best way to locate a material-ui slider within a react

I am seeking to incorporate multiple material-ui sliders into a single react component that share a common event handler. However, I have encountered difficulties in identifying which slider triggered the event. Despite referring to the API documentation, ...

Use jQuery to change the background color when clicked

Below is the HTML code with UL and LI elements: <UL> <LI><span id='select1'>Text</span></LI> <LI><span id='select2'>Text</span></LI> <LI><span id='select3'>Tex ...

Utilizing JavaScript or jQuery in MVC4 to showcase information for the primary record

I'm currently working on constructing a page that displays a list of users. My aim is to have a "Details" link in each row that, when clicked, will render a partial view on the same page without having to reload it using either javascript or jQuery. D ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...