Why Typeahead shows json object in input after click
Asked Answered
H

1

6

My suggestion engine works fine, I just have a problem because when I click on item its json object appears in input element. I would like only OrgName to appear in input value.

<input class="form-control companySearch" type="text" value="" name="q" autocomplete="off" placeholder="Search a company">

var organization = new Bloodhound({
        remote: {
            url: '/search/org?term=%QUERY%',
            wildcard: '%QUERY%'
        },
        datumTokenizer: Bloodhound.tokenizers.whitespace('term'),
        queryTokenizer: Bloodhound.tokenizers.whitespace
    });
$(".companySearch").typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
    },
        {
            source: organization.ttAdapter(),       
            name: 'organizationsList',            
            templates: {                
                suggestion: function (data) {        
                    return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country  + '</a>';                

                }
            }

        }
    );

Example how I get

Hamnet answered 16/3, 2017 at 18:4 Comment(0)
S
9

I had a similar problem and solved it using the typeahead's display attribute.

In your example:

$(".companySearch").typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
    },
        {
            source: organization.ttAdapter(),       
            name: 'organizationsList',
            display: 'id', // PUT IT HERE
            templates: {                
                suggestion: function (data) {        
                    return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country  + '</a>';                

                }
            }    
        }
    );

From the docs:

display – For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to stringifying the suggestion.

If it doesn't work, try replace display for displayKey (I think that is something on the typeahead's versions).

Slingshot answered 26/7, 2017 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.