0

Tenho o seguinte código js que prepara um campo de pesquisa usando o 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>')
    }
});

Como eu pego o valor do atributo data-value? Até tentei uma solução usando a função bind() mas sem sucesso, veja ele abaixo.

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

Obs: meu problema não está em pegar um valor de um atributo data-em si.

1 Resposta 1

1

O evento typeahead:selected não existe, o correto seria typeahead:select, para pegar o valor da array, use o segundo argumento (valor que é exibido no input):

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

Para pegar o atributo data-value (eu não sei ao certo se é o mesmo valor do input), use .parent() do jQuery e com o seletor .result-values que equivale ao seu template:

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

Deve ficar algo como

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

Ou usando o .data:

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

Os eventos suportados atualmente pelo typeahead são typeahead:active, typeahead:idle, typeahead:open, typeahead:close, typeahead:change, typeahead:render, typeahead:select, typeahead:autocomplete, typeahead:cursorchange, typeahead:asyncrequest, typeahead:asynccancel e typeahead:asyncreceive.

Documentação: https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .