Typeahead.js: Example of typeahead:selected event

Created on 21 Jun 2013  路  40Comments  路  Source: twitter/typeahead.js

For anyone interested until an example is added to documentation for custom events...

Assuming there's an input on your page called 'search_input':

$('#search_input').bind('typeahead:selected', function(obj, datum, name) {      
        alert(JSON.stringify(obj)); // object
        // outputs, e.g., {"type":"typeahead:selected","timeStamp":1371822938628,"jQuery19105037956037711017":true,"isTrigger":true,"namespace":"","namespace_re":null,"target":{"jQuery19105037956037711017":46},"delegateTarget":{"jQuery19105037956037711017":46},"currentTarget":
        alert(JSON.stringify(datum)); // contains datum value, tokens and custom fields
        // outputs, e.g., {"redirect_url":"http://localhost/test/topic/test_topic","image_url":"http://localhost/test/upload/images/t_FWnYhhqd.jpg","description":"A test description","value":"A test value","tokens":["A","test","value"]}
        // in this case I created custom fields called 'redirect_url', 'image_url', 'description'   

        alert(JSON.stringify(name)); // contains dataset name
        // outputs, e.g., "my_dataset"

});

https://github.com/twitter/typeahead.js#custom-events

Most helpful comment

I was banging my head against the wall so... please note that now the event is "typeahead:select" and NO LONGER "selected".. after this, the original example still works and is the correct way to do it, thanks!

All 40 comments

What would be even better would be a pull request that added this to the README :smile: see #174.

Agreed, this should be in the README

Yup, please add this to the documentation.

Thanks, been looking for this :)

Yea, thanks, found this via google after finding docs insufficient.

Nice.... why this is not in the documentation yet?

Wow, been fighting with this thing, thanks A LOT for the info!

:+1: to add it to the readme

@pouipouidesign I've forgotten what this was about aready ;) Can you please spend 5 mins to edit the README & any examples and do a PR?

I will, but over this w-e as I'm in the middle of a sprint of a sort (hence my relief at findings this).
I'll just have to pester my husband for info about doing a PR, as I've never done it before :)

I understand that when jharding and I first commented this example didn't have enough attention to make its way to the README, but it's about time it does so, no?

@pouipouidesign I'd be happy to help, I just forgot about the context & don't feel I could correctly represent the issue any more. If you need any help with the PR let me know. I'm insertcoffee on twitter.

Alternatively can people put some info in the comments here and I will compile it in to a PR.

Lot of things will be appreciated in the README and in the exemples like valueKey or tokens usage

There is one more parameter in callback function - dataset name. Can you add it to your example?

Thanks so much! Just what I needed.

@antimony Added dataset name parameter, thanks.

I haven't forgotten to do this, just been swamped.
Have good hope of doing it this w-e.
Sorry for the delay.
If anyone wants to do it faster, please do :)

As a note, I have not been able to find documentation on this and had to add a .off('blur') to the stack to make sure the value does not revert to the selected value.

 $('.user-typeahead').typeahead({
    remote: '/ajax_user_typeahead?query=%QUERY''
}).bind('typeahead:selected', function(obj, selected, name) {
    if (selected.value.toString().split('-').length > 1) { /* "name - [email protected]" */
        $(this).val(selected.value.toString().split('-')[0].replace(/^\s+|\s+$/g, '')); /* split, select, trim */
    }
    return false; /* didn't do anything, maybe not necessary */
}).off('blur');

@wallter if you went to set the value of the typeahead input control, use jQuery#typeahead('val', yourVal). See https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#jquerytypeaheadval-val

I'm trying to get the val of the typeahead instance on selected but I keep getting undefined

$(scope.conf.field).on('typeahead:selected' , function(e,s,d)
{ console.log($(scope.conf.field).typeahead('val'); });

This keeps returning undefined. Anything else inside that event happens fine, just returns undefined for the value of typeahead. Not sure what I've done wrong...

Any reason why you're trying to get the value that way rather than getting it from the suggestion object passed to the event handler i.e. the s argument in your sample code?

That's a good point, I got it working now by using $(this) instead (not entirely sure why that works as it SHOULD be equivalent to what I was selecting previously) but yeah, I should be using s.

With the above method I get a "Supplied parameters do not match any signature of call target: Call signatures of types ' => void' and ' => any' are incompatible. Call signature expects 1 or fewer parameters" error.

Here is my code - $("input[name='myTypeAhead']").bind("typeahead:selected", function(obj, datum, name) {
console.log("selected");
});

Any idea what am doing wrong here?

@maanasa Give this a shot? Looks like you were binding to the input field itself rather than the typeahead object.

$('#field_id').typeahead({
  highlight: true
},
{
  name: 'first_dataset',
  displayKey: 'name',
  source: first_dataset.ttAdapter(),
  templates: {
    header: '<b>first_dataset</b><hr />'
  }
},
{
  name: 'second_dataset',
  displayKey: 'name',
  source: second_dataset.ttAdapter(),
  templates: {
    header: '<b>second_dataset</b><hr />'
  }
}).bind("typeahead:selected", function(obj, datum, name) {
console.log(obj, datum, name);
});

Tnx loads, was looking for this.

Hey!
how to display some default datasets just on clicking mouse on textbox using typeahead.js?

@HiteshDhanwani There's already an issue #798. Here's a working fiddle, but I couldn't get it working using Bloodhound as engine.

Excellent, thanks man !! :) :100:

Exactly what I was looking for - why is this not in the docs under custom events? There's no example available.

Am I wrong or this is not working anymore?

Thanks man.

+1

Since the "overhaul" of typeahead, typeahead:select no longer defines the dataset name. Anyone know how to get the dataset on the select event?

I was banging my head against the wall so... please note that now the event is "typeahead:select" and NO LONGER "selected".. after this, the original example still works and is the correct way to do it, thanks!

I am getting: TypeError: cyclic object value from:

.on('typeahead:selected', function(obj, datum, name) { 
console.log(JSON.stringify(obj));
console.log(JSON.stringify(datum));
console.log(JSON.stringify(name));

typeahead.bundle.min.js at v0.10.5.

+1 to @mtzmedia question. I need to determine which dataset the selection belongs to. I can't seem to find this information anywhere. I got my hopes up seeing this example, only to realize this is an old thread and the name is no longer an argument. Anyone know of another way?

Hi,
I'm trying to use this hint but without success. The typeahead selector works perfectly (it's a multi-dataset typeahead) but no events are fired.

The following is the HTML part:

<div id="namelist">
          <input class="typeahead" id="searchinput" type="text" placeholder=" search a name..." style="padding:3px">
        </div>

and this is the javascript part to bind the selected event but it doesn't fire anything.

$('#namelist .typeahead').bind('typeahead:selected', function (obj, datum, name) {
            alert(JSON.stringify(obj)); 
            alert(JSON.stringify(datum)); 
            alert(JSON.stringify(name)); 
        });

I have also tried to reference directly the input:

$('#searchinput').bind('typeahead:selected', function (obj, datum, name) {
            alert(JSON.stringify(obj)); 
            alert(JSON.stringify(datum)); 
            alert(JSON.stringify(name)); 
        });

Nothing.

Any help?

thanks.

@mlosavio see ZaneCEO's comment above.

nothing, it doesn't work.
I'm sure I'm missing something...
Is there anyone who could post a full example please?

thanks.

Try:

  • focus.bootstrap3Typeahead
  • blur.bootstrap3Typeahead
  • keypress.bootstrap3Typeahead
  • propertychange.bootstrap3Typeahead input.bootstrap3Typeahead
  • keyup.bootstrap3Typeahead

Like:

$('input.typeahead').typeahead({...}).bind('keyup.bootstrap3Typeahead', function(event, dataset_selected_Item, dataset_name) {
    console.log('keyup');
  });

NOTE: In the latest version of typeahead, typeahead:selected has been changed to typeahead:select and now only two params are passed instead of three: ( event, selected_object )

Was this page helpful?
0 / 5 - 0 ratings

Related issues

steswinbank picture steswinbank  路  5Comments

a-lucas picture a-lucas  路  5Comments

viktor-rachuk picture viktor-rachuk  路  3Comments

DevChive picture DevChive  路  5Comments

GreatPotato picture GreatPotato  路  8Comments