Working Twitter-Typeahead Example

Working twitter-typeahead example?

Specify gem as dependency in your Gemfile:

# Gemfile

gem 'bootstrap-multiselect-rails'

Require typeahead files in your manifest:

// app/assets/javascripts/application.js

//= require twitter/typeahead
//= require twitter/typeahead/bloodhound

Javascript:

// app/assets/javascripts/models_controller.js

// initialize bloodhound engine
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,

// sends ajax request to /typeahead/%QUERY
// where %QUERY is user input
remote: '/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();

// initialize typeahead widget and hook it up to bloodhound engine
// #typeahead is just a text input
$('#typeahead').typeahead(null, {
displayKey: 'name',
source: bloodhound.ttAdapter()
});

// this is the event that is fired when a user clicks on a suggestion
$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
doSomething(datum.id);
});

View:

<-- app/views/models/whatever.html.erb -->

<input type="text" id="typeahead">

Routes:

# config/routes.rb

get 'typeahead/:query' => 'models#typeahead'

Controller:

# app/controllers/models_controller.rb

def typeahead
render json: Model.where(name: params[:query])
end

## note: the above will only return exact matches.
## depending on the database being used,
## something else may be more appropriate.
## here is an example for postgres
## for case-insensitive partial matches:

def typeahead
render json: Model.where('name ilike ?', "%#{params[:query]}%")
end

GET request to /typeahead/%QUERY returns json in the form of:

[
{
"name": "foo",
"id": "1"
},
{
"name": "bar",
"id": "2"
}
]

How to use of typeahead example?

Your problem is the order you're loading the JS libraries.

Put

<script src="js/typeahead.bundle.js"></script>

either after

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    

or after

<script src="js/bootstrap.min.js"></script>

Either way should fix your issue.

Twitter Typeahead Highlighting

It seems a lot of people are having the problem of not specifying the required parameter minLength: x.

In your case, you've already done this. The problem is that you need to add the following to CSS

.tt-cursor {
color: #f1b218;
}

Twiiter Typeahead Custom Templates - Getting Default Example Working

Try using Bloodhound , returning object bestPictures as a property accessible at .typeahead suggestions function

jQuery(document).ready(function() {
var bestPictures = [{ "year": "1996", "value": "Tom", "url": "http://example.com" }, { "year": "1998", "value": "Tim", "url": "http://example.com" }];
var pictures = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"), queryTokenizer: Bloodhound.tokenizers.whitespace, local: $.map(bestPictures, function(d) { return { value: d.value, // pass `bestPictures` to `suggestion` suggest: d } }) });
pictures.initialize();
$("#custom-templates .typeahead").typeahead(null, { name: "best-pictures", display: "value", source: pictures.ttAdapter(), templates: { notFound: [ "<div class=empty-message>", "unable to find any Best Picture winners that match the current query", "</div>" ].join("\n"), suggestion: function(data) { // `data` : `suggest` property of object passed at `Bloodhound` return "<div><strong>" + data.suggest.value + "</strong>" + data.suggest.year + "</div>" } } });});
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script><script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div id="custom-templates"> <input type="text" class="typeahead" placeholder="Best picture winners" /></div>

Twitter Typeahead Not autocompleting when I continue typing

I finally fixed this issue by creating a variable called FullName which is a concatenation of first name, middle name and last name. Then, I used it as a datumtokenizer instead of just first name.

Using Twitter Typeahead in ASP.net MVC

We should use Bloodhound's ttAdapter which comes from typeahead bundle and
can capture the selected suggestion-item from typeahead:selected event.

Below is the script for your reference:

TestCase#1 with local dataset Working fiddle

<label for="company_search">Company Search:</label>
<input id="company_search" type="text" class="typeahead" />
<div id="selectedCompany"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/0.10.4/typeahead.bundle.js"></script>
<script>
$(function () {
var $SelectedCompany = $('#selectedCompany').hide(),
companyList = [{"Key":1,"Value":"Test1"},{"Key":2,"Value":"Test2)"},{"Key":4,"Value":"Adagreb d.o.o."},{"Key":5,"Value":"AGB Nielsen."}];

var companies = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: companyList
//,prefetch: '/path/to/prefetch'
//,remote: {/* You can use this for ajax call*/ }
});

companies.initialize();

$('#company_search').typeahead({ highlight: true, minLength: 2 }, {
name: 'companies', displayKey: 'Value', source: companies.ttAdapter()
})
.on("typeahead:selected", function (obj, company) {
$SelectedCompany.html("Selected Company: " + JSON.stringify(company)).show();
});

});
</script>

Edit:

TestCase#2 with remote dataset Working fiddle

<input class="typeahead" placeholder="Type here to Search Movie..."></input>
<div id="selectedSuggestion"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/0.10.4/typeahead.bundle.js"></script>
<script>
$(function () {
//Docs: https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote
var $SelectedSuggestion = $('#selectedSuggestion').hide(),
movies = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.title);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'http://api.themoviedb.org/3/search/movie?query=%QUERY&api_key=470fd2ec8853e25d2f8d86f685d2270e',
filter: function (movies) {
return movies.results;
}
}
});

// Initialize the Bloodhound suggestion engine
movies.initialize();

// Instantiate the Typeahead UI
$('.typeahead').typeahead(null, {
displayKey: 'title',
source: movies.ttAdapter()
})
.on("typeahead:selected", function (obj, selectedItem) {
$SelectedSuggestion.html("Selected Suggestion Item: " + JSON.stringify(selectedItem)).show();
});
});
</script>

Twitter-Bootstrap typeahead not working

The typeahead function was removed from Bootstrap in v3. According to @mdo it was dropped "in favor of folks using Twitter's typeahead. Twitter's typeahead has more features than the old bootstrap-typeahead.js and less bugs."

Your two options from here are:

  1. Use a port of Bootstrap v2 Typeahead, you can find one here.

  2. Use Twitter Typeahead which can be found here.

twitter typeahead Force selection with prefetched content

I don't know any straight forward solution for this but I guess I can provide a workaround.

You can clear the hidden input on change() event, it will be updated on typeahead:selected event later:

$('.cp').typeahead({                              
name: 'nom',
prefetch: 'ajax_recherche_ville.php',
limit: 50
}).change(function () {
$('input[name=ville_id]').val(''); // don't use :hidden since it slow down performance and doesn't do anything special, I suppose the input with name ville_id is unique
}).bind('typeahead:selected', function(obj, datum) {
$('input[name=ville_id]').val(datum.id);
});

The weak spot of this method are:

  • It doesn't clear the typeahead input if user input something that doesn't trigger the autocomplete
  • The user has to click on the autocomplete dropdown (trigger typeahead:selected) in order for the hidden input to populate

Demo: http://jsfiddle.net/hieuh25/zz85q/

Hope it helps.



Related Topics



Leave a reply



Submit