Skip to content

Instantly share code, notes, and snippets.

@lucasdavila
Created October 16, 2012 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasdavila/3899587 to your computer and use it in GitHub Desktop.
Save lucasdavila/3899587 to your computer and use it in GitHub Desktop.
asynchronous twitter bootstrap typeahead
Typeahead is a javascript plugin from Twitter Bootstrat [1] that allows quickly creating typeaheads with any
form text input element.
[1] http://twitter.github.com/bootstrap/javascript.html#typeahead
# in html view
<%= text_field @student, :name, 'data-provide' => 'typeahead',
'data-source' => '["option_1", "option_2"]' %>
# in html view
<%= text_field :student, :name, 'data-provide' => 'typeahead' %>
# in js asset
var options = {
source: ['option_1', 'option_2']
};
$('#student_name').typeahead(options);
# please, note that in this example we don't make difference between the value and the label, in another words
# the value of the input is what the user see.
# in html view
<%= text_field :student, :name, 'data-provide' => 'typeahead' %>
# in js asset
var options = {
source: function (query, process) {
// asynchronous call using jquery, that responds with { 'options' : ['option_1', 'option_2'] };
$.get('<%= students_search_path :format => :json %>', { query: query }, function(data) {
process(data.options);
});
}
};
$('#student_name').typeahead(options);
# please note that in this example we have id and label for the input, in another words the value of the input
# is different from what the user see.
# in html view
<%= text_field :student, :name, 'data-provide' => 'typeahead' %>
<%= hidden_field :student, :id %>
# in js asset
var labels, mapped;
var options = {
source: function (query, process) {
// asynchronous call using jquery, that responds with
// { 'options' : { 'id_1': 'id_1 - value_1', 'id_2': 'id_2 - value_2' } };
$.get('<%= students_search_path :format => :json %>', { query: query }, function(data) {
labels = [];
mapped = {};
$.each(data.options, function (key, value) {
if (mapped[value] != undefined)
throw "'" + value + "' already defined in mapped hash.";
mapped[value] = key;
labels.push(value);
});
process(labels);
});
},
updater: function (item) {
var key = mapped[item];
$('#student_id').val(key);
return item;
}
};
$('#student_name').typeahead(options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment