Adding a click event on a Twitter Typeahead result

0

I have the following js code that prepares a search field using Twitter Typeahead :

var users = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('cname'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: 'application/controller/TypeaheadSeed.php?QUERY=%QUERY'
});
users.initialize();

$('#input-friend-list-publication').typeahead({
    hint: true,
    highlight: true
}, {
    name: 'users',
    displayKey: 'cname',
    source: users.ttAdapter(),
    templates: {
        header: '<div class="tt-header">Meus amigos</div>',
        empty: [
            '<div class="empty-message">',
            '   Não foi possível encontrar resultados para essa pesquisa.',
            '</div>'
        ].join('\n'),
        suggestion: Handlebars.compile(
            '<div class="result-values" style="display: inline-block; vertical-align: top;" data-value="{{username}}">' +
            '    <img class="img-rounded" src="{{profilepicpath}}" alt="{{cname}}" title="{{cname}}" width="48" height="48" />' +
            '</div>' +
            '<div style="display: inline-block; vertical-align: top; margin-left: 10px">' +
            '    <div>{{cname}}</div>' +
            '</div>')
    }
});

How do I get the value of the data-value attribute? Even tried a solution using the bind() function but without success, see below.

$('#input-friend-list-publication').bind('typeahead:selected', function () {
    console.log($(this));
});

Note: My problem is not to get a value of an attribute data- itself.

    
asked by anonymous 29.05.2015 / 02:25

1 answer

1

The event typeahead:selected does not exist, the correct one would be typeahead:select , to get the value of the array, use the second argument (value that is displayed in the input):

$('#input-friend-list-publication').bind('typeahead:select', function (targetEvent, value) {
    console.log(value);
});

To get the attribute data-value (I'm not sure if it's the same value as the input), use .parent() of jQuery and with the .result-values selector that matches your template:

 <div class="result-values" ...

It should look something like

$('#input-friend-list-publication').bind('typeahead:select', function (targetEvent, value) {
    var target = $(this).parent();
    console.log($(".result-values", target).attr("data-value"));
});

Or using .data :

$('#input-friend-list-publication').bind('typeahead:select', function (targetEvent, value) {
    var target = $(this).parent();
    console.log($(".result-values", target).data("value"));
});

Events currently supported by typeahead are typeahead:active , typeahead:idle , typeahead:open , typeahead:close , typeahead:change , typeahead:render , typeahead:select , typeahead:autocomplete , typeahead:cursorchange , typeahead:asyncrequest , typeahead:asynccancel and typeahead:asyncreceive .

Documentation: link

    
26.06.2015 / 06:28