Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Typeahead shows json object in input after click

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

like image 309
Dejan Avatar asked Mar 16 '17 18:03

Dejan


1 Answers

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).

like image 51
James Avatar answered Nov 04 '22 23:11

James