typeahead在bootstrap typeahead的哪个模块

bootstrap - typeahead自动补全插件
来源:博客园

 $('#Sale').typeahead({
ajax: {
url: '@Url.Action("../Contract/GetSale")',
//timeout: 300,
method: 'post',
triggerLength: 1,
loadingClass: null,
preProcess: function (result) {
return
display: "Value",
val: "ID",
items: 10,
itemSelected: function (item, val, text) {
$("#SalesID").val(val);
});

这种 typeahead自动补全不是bootstrap常用的typeahead.js。 以下是typeahead.js代码(如果有bootstrap3-typeahead.js更好)

//
----------------------------------------------------------------------------
//
//
bootstrap-typeahead.js

//
//
Twitter Bootstrap Typeahead Plugin
//
v1.2.2
//
/tcrosen/twitter-bootstrap-typeahead
//
//
//
Author
//
----------
//
Terry Rosen
//
| @rerrify | /tcrosen/
//
//
//
Description
//
----------
//
Custom implementation of Twitter's Bootstrap Typeahead Plugin
//
/bootstrap/javascript.html#typeahead
//
//
//
Requirements
//
----------
//
jQuery 1.7+
//
Twitter Bootstrap 2.0+
//
//
----------------------------------------------------------------------------

!
function ($) {

"use strict";

//------------------------------------------------------------------
Constructor
var Typeahead = function (element, options) {
this.$element = $(element);
this.options = $.extend(true, {}, $.fn.typeahead.defaults, options);
this.$menu = $(this.options.menu).appendTo('body');
this.shown = false;

// Method overrides
this.eventSupported = this.options.eventSupported || this.eventS
this.grepper = this.options.grepper || this.
this.highlighter = this.options.highlighter || this.
this.lookup = this.options.lookup || this.
this.matcher = this.options.matcher || this.
this.render = this.options.render || this.
this.select = this.options.select || this.select;
this.sorter = this.options.sorter || this.
this.source = this.options.source || this.

if (!this.source.length) {
var ajax = this.options.

if (typeof ajax === 'string') {
this.ajax = $.extend({}, $.fn.typeahead.defaults.ajax, { url: ajax });
} else {
this.ajax = $.extend({}, $.fn.typeahead.defaults.ajax, ajax);
}

if (!this.ajax.url) {
this.ajax = null;
}

this.listen();
}

Typeahead.prototype = {

constructor: Typeahead,

//=============================================================================================================
Utils
//=============================================================================================================

//------------------------------------------------------------------
Check if an event is supported by the browser eg. 'keypress'
* This was included to handle the "exhaustive deprecation" of jQuery.browser in jQuery 1.8
eventSupported: function (eventName) {
var isSupported = (eventName in this.$element);

if (!isSupported) {
this.$element.setAttribute(eventName, '');
isSupported = typeof this.$element[eventName] === 'function';
}

return isS
},

//=============================================================================================================
//=============================================================================================================

//------------------------------------------------------------------
Handle AJAX source 
ajaxer: function () {
var that = this,
query = that.$element.val();

if (query === that.query) {
return
}

// Query changed
that.query =

// Cancel last timer if set
if (that.ajax.timerId) {
clearTimeout(that.ajax.timerId);
that.ajax.timerId = null;
}

if (!query || query.length & that.ajax.triggerLength) {
// Cancel the ajax callback if in progress
if (that.ajax.xhr) {
that.ajax.xhr.abort();
that.ajax.xhr = null;
that.ajaxToggleLoadClass(false);
}

return that.shown ? that.hide() :
}

// Query is good to send, set a timer
that.ajax.timerId = setTimeout(function () {
$.proxy(that.ajaxExecute(query), that)
}, that.ajax.timeout);

return
},

//------------------------------------------------------------------
Execute an AJAX request
ajaxExecute: function (query) {
this.ajaxToggleLoadClass(true);

// Cancel last call if already in progress
if (this.ajax.xhr) this.ajax.xhr.abort();

var params = this.ajax.preDispatch ? this.ajax.preDispatch(query) : { query: query };
var jAjax = (this.ajax.method === "post") ? $.post : $.get;
this.ajax.xhr = jAjax(this.ajax.url, params, $.proxy(this.ajaxLookup, this));
this.ajax.timerId = null;
},

//------------------------------------------------------------------
Perform a lookup in the AJAX results
ajaxLookup: function (data) {
var

this.ajaxToggleLoadClass(false);

if (!this.ajax.xhr) return;

if (this.ajax.preProcess) {
data = this.ajax.preProcess(data);
}

// Save for selection retreival
this.ajax.data =

items = this.grepper(this.ajax.data);

if (!items || !items.length) {
return this.shown ? this.hide() : this;
}

this.ajax.xhr = null;

return this.render(items.slice(0, this.options.items)).show();
},

//------------------------------------------------------------------
Toggle the loading class
ajaxToggleLoadClass: function (enable) {
if (!this.ajax.loadingClass) return;
this.$element.toggleClass(this.ajax.loadingClass, enable);
},

//=============================================================================================================
Data manipulation
//=============================================================================================================

//------------------------------------------------------------------
Search source
lookup: function (event) {
var that = this,
 

if (that.ajax) {
that.ajaxer();
else {
that.query = that.$element.val();

if (!that.query) {
return that.shown ? that.hide() :
}

items = that.grepper(that.source);

if (!items || !items.length) {
return that.shown ? that.hide() :
}

return that.render(items.slice(0, that.options.items)).show();
},

//------------------------------------------------------------------
Filters relevent results 
grepper: function (data) {
var that = this,
 

if (data && data.length && !data[0].hasOwnProperty(that.options.display)) {
return null;
}

items = $.grep(data, function (item) {
return that.matcher(item[that.options.display], item);
});

return this.sorter(items);
},

//------------------------------------------------------------------
Looks for a match in the source
matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase());
},

//------------------------------------------------------------------
Sorts the results
sorter: function (items) {
var that = this,
beginswith = [],
caseSensitive = [],
caseInsensitive = [],


while (item = items.shift()) {
if (!item[that.options.display].toLowerCase().indexOf(this.query.toLowerCase())) {
beginswith.push(item);
else if (~item[that.options.display].indexOf(this.query)) {
caseSensitive.push(item);
else {
caseInsensitive.push(item);
}

return beginswith.concat(caseSensitive, caseInsensitive);
},

//=============================================================================================================
DOM manipulation
//=============================================================================================================

//------------------------------------------------------------------
Shows the results list
show: function () {
var pos = $.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});

this.$menu.css({
top: pos.top + pos.height,
left: pos.left
});

this.$menu.show();
this.shown = true;

return this;
},

//------------------------------------------------------------------
Hides the results list
hide: function () {
this.$menu.hide();
this.shown = false;
return this;
},

//------------------------------------------------------------------
Highlights the match(es) within the results
highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '&strong&' + match + '&/strong&';
},

//------------------------------------------------------------------
Renders the results list
render: function (items) {
var that = this;

items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item[that.options.val]);
i.find('a').html(that.highlighter(item[that.options.display], item));
return i[0];
});

items.first().addClass('active');
this.$menu.html(items);
return this;
},

//------------------------------------------------------------------
Item is selected
select: function () {
var $selectedItem = this.$menu.find('.active');
this.$element.val($selectedItem.text()).change();
this.options.itemSelected($selectedItem, $selectedItem.attr('data-value'), $selectedItem.text());
return this.hide();
},

//------------------------------------------------------------------
Selects the next result
next: function (event) {
var active = this.$menu.find('.active').removeClass('active');
var next = active.next();

if (!next.length) {
next = $(this.$menu.find('li')[0]);
}

next.addClass('active');
},

//------------------------------------------------------------------
Selects the previous result
prev: function (event) {
var active = this.$menu.find('.active').removeClass('active');
var prev = active.prev();

if (!prev.length) {
prev = this.$menu.find('li').last();
}

prev.addClass('active');
},

//=============================================================================================================
Events
//=============================================================================================================

//------------------------------------------------------------------
Listens for user events
listen: function () {
this.$element.on('blur', $.proxy(this.blur, this))
.on('keyup', $.proxy(this.keyup, this));

if (this.eventSupported('keydown')) {
this.$element.on('keydown', $.proxy(this.keypress, this));
} else {
this.$element.on('keypress', $.proxy(this.keypress, this));
}

this.$menu.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this));
},

//------------------------------------------------------------------
Handles a key being raised up
keyup: function (e) {
e.stopPropagation();
e.preventDefault();

switch (e.keyCode) {
case 40:
// down arrow
case 38:
// up arrow
break;
case 9:
// tab
case 13:
// enter
if (!this.shown) {
return;
this.select();
break;
case 27:
// escape
this.hide();
break;
default:
this.lookup();
},

//------------------------------------------------------------------
Handles a key being pressed
keypress: function (e) {
e.stopPropagation();
if (!this.shown) {
return;
}

switch (e.keyCode) {
case 9:
// tab
case 13:
// enter
case 27:
// escape
e.preventDefault();
break;
case 38:
// up arrow
e.preventDefault();
this.prev();
break;
case 40:
// down arrow
e.preventDefault();
this.next();
break;
},

//------------------------------------------------------------------
Handles cursor exiting the textbox
blur: function (e) {
var that = this;
e.stopPropagation();
e.preventDefault();
setTimeout(function () {
if (!that.$menu.is(':focus')) {
that.hide();
}, 150)
},

//------------------------------------------------------------------
Handles clicking on the results list
click: function (e) {
e.stopPropagation();
e.preventDefault();
this.select();
},

//------------------------------------------------------------------
Handles the mouse entering the results list
mouseenter: function (e) {
this.$menu.find('.active').removeClass('active');
$(e.currentTarget).addClass('active');
}

//------------------------------------------------------------------
Plugin definition
$.fn.typeahead = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('typeahead'),
options = typeof option === 'object' &&

if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}

if (typeof option === 'string') {
data[option]();
}

//------------------------------------------------------------------
Defaults
$.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '&ul class="typeahead dropdown-menu"&&/ul&',
item: '&li&&a rel="nofollow" href="#"&&/a&&/li&',
display: 'name',
val: 'id',
itemSelected: function () { },
ajax: {
url: null,
timeout: 300,
method: 'post',
triggerLength: 3,
loadingClass: null,
displayField: null,
preDispatch: null,
preProcess: null
}

$.fn.typeahead.Constructor = T

//------------------------------------------------------------------
DOM-ready call for the Data API (no-JS implementation)
Note: As of Bootstrap v2.0 this feature may be disabled using $('body').off('.data-api')
More info here: /twitter/bootstrap/tree/master/js
$(function () {
$('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this);

if ($this.data('typeahead')) {
return;
}

e.preventDefault();
$this.typeahead($this.data());
});

}(window.jQuery);

免责声明:本站部分内容、图片、文字、视频等来自于互联网,仅供大家学习与交流。相关内容如涉嫌侵犯您的知识产权或其他合法权益,请向本站发送有效通知,我们会及时处理。反馈邮箱&&&&。
学生服务号
在线咨询,奖学金返现,名师点评,等你来互动jquery - twitter bootstrap typeahead ajax example - Stack Overflow
Join the Stack Overflow Community
Stack Overflow is a community of 7.0 million programmers, just like you, helping each other.
J it only takes a minute:
I'm trying to find a working example of the
element that will make an ajax call to populate it's dropdown.
I have an existing working jquery autocomplete example which defines the ajax url to and how to process the reply
&script type="text/javascript"&
//&![CDATA[
$(document).ready(function() {
var options = { minChars:3, max:20 };
$("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
function(event, data, formatted)
window.location = "./runner/index/id/"+data[1];
What do i need change to convert this to the typeahead example?
&script type="text/javascript"&
//&![CDATA[
$(document).ready(function() {
var options = { source:'/index/runnerfilter/format/html', items:5 };
$("#runnerquery").typeahead(options).result(
function(event, data, formatted)
window.location = "./runner/index/id/"+data[1];
I'm going to wait for the '' issue to be resolved.
7,83755369
4,9191366121
Edit: typeahead is no longer bundled in Bootstrap 3. Check out:
As of Bootstrap 2.1.0 up to 2.3.2, you can do this:
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('/typeahead', { query: query }, function (data) {
return process(data.options);
To consume JSON data like this:
"options": [
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5"
Note that the JSON data must be of the right mime type (application/json) so jQuery recognizes it as JSON.
3,77812032
You can use the
which supports ajax calls.
Then you will be able to write:
$('.typeahead').typeahead({
source: function (typeahead, query) {
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
3,77812032
1,47811016
Starting from Bootstrap 2.1.0:
&input type='text' class='ajax-typeahead' data-link='your-json-link' /&
Javascript:
$('.ajax-typeahead').typeahead({
source: function(query, process) {
return $.ajax({
url: $(this)[0].$element[0].dataset.link,
type: 'get',
data: {query: query},
dataType: 'json',
success: function(json) {
return typeof json.options == 'undefined' ? false : process(json.options);
Now you can make a unified code, placing "json-request" links in your HTML-code.
All of the responses refer to BootStrap 2 typeahead, which is no longer present in BootStrap 3.
For anyone else directed here looking for an AJAX example using the new post-Bootstrap , here's a working example. The syntax is a little different:
$('#mytextquery').typeahead({
hint: true,
highlight: true,
minLength: 1
limit: 12,
async: true,
source: function (query, processSync, processAsync) {
processSync(['This suggestion appears immediately', 'This one too']);
return $.ajax({
url: "/ajax/myfilter.php",
type: 'GET',
data: {query: query},
dataType: 'json',
success: function (json) {
// in this example, json is simply an array of strings
return processAsync(json);
This example uses both synchronous (the call to processSync) and asynchronous suggestion, so you'd see some options appear immediately, then others are added. You can just use one or the other.
There are lots of bindable events and some very powerful options, including working with objects rather than strings, in which case you'd use your own custom display function to render your items as text.
I've augmented the original typeahead Bootstrap plugin with ajax capabilities. Very easy to use:
$("#ajax-typeahead").typeahead({
ajax: "/path/to/source"
Here's the github repo:
5,33163460
I did some modifications on the jquery-ui.min.js:
//Line 319 ORIG:
this.menu=d("&ul&&/ul&").addClass("ui-autocomplete").appendTo(d(...
this.menu=d("&ul&&/ul&").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...
// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....
// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`
and add following css
.dropdown-menu {
max-width: 920
.ui-menu-item {
Works perfect.
3,02211432
To those looking for a coffeescript version of the accepted answer:
$(".typeahead").typeahead source: (query, process) -&
$.get "/typeahead",
query: query
, (data) -&
process data.options
2,10432842
I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.
&?php if (isset($_GET['typeahead'])){
die(json_encode(array('options' =& array('like','spike','dike','ikelalcdass'))));
&link href="bootstrap.css" rel="stylesheet"&
&input type="text" class='typeahead'&
&script src="jquery-1.10.2.js"&&/script&
&script src="bootstrap.min.js"&&/script&
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('index.php?typeahead', { query: query }, function (data) {
return process(JSON.parse(data).options);
I am using this method
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
name: 'options',
displayKey: 'value',
source: function (query, process) {
return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
var matches = [];
$.each(data, function(i, str) {
matches.push({ value: str });
return process(matches);
},'json');
UPDATE: I modified my code using
also instead of using $.each I changed to $.map as suggested by Tomislav Markovski
$('#manufacturer').typeahead({
source: function(typeahead, query){
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new A
$.map(results.data.manufacturers, function(data, item){
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
manufacturers.push(group);
typeahead.process(manufacturers);
property: 'name',
onselect: function (obj) {
However I am encountering some problems by getting
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
as you can see on a newer post I am trying to figure out
hope this update is of any help to you...
One can make calls by using Bootstrap. The current version does not has any source update issues
, i.e. the source of bootstrap once updated can be again modified.
Please refer to below for an example:
jQuery('#help').typeahead({
source : function(query, process) {
jQuery.ajax({
url : "urltobefetched",
type : 'GET',
"query" : query
dataType : 'json',
success : function(json) {
process(json);
minLength : 1,
Try this if your service is not returning the right application/json content type header:
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('/typeahead', { query: query }, function (data) {
var json = JSON.parse(data); // string to json
return process(json.options);
I don't have a working example for you nor do I have a very clean solution, but let me tell you what I've found.
If you look at the javascript code for TypeAhead it looks like this:
items = $.grep(this.source, function (item) {
if (that.matcher(item)) return item
This code uses the jQuery "grep" method to match an element in the source array. I didn't see any places you could hook in an AJAX call, so there's not a "clean" solution to this.
However, one somewhat hacky way that you can do this is to take advantage of the way the grep method works in jQuery. The first argument to grep is the source array and the second argument is a function that is used to match the source array (notice Bootstrap calls the "matcher" you provided when you initialized it). What you could do is set the source to a dummy one-element array and define the matcher as a function with an AJAX call in it. That way, it will run the AJAX call just once (since your source array only has one element in it).
This solution is not only hacky, but it will suffer from performance issues since the TypeAhead code is designed to do a lookup on every key press (AJAX calls should really only happen on every few keystrokes or after a certain amount of idle time). My advice is to give it a try, but stick with either a different autocomplete library or only use this for non-AJAX situations if you run into any problems.
when using ajax, try $.getJSON() instead of $.get() if you have trouble with the correct display of the results.
In my case i got only the first character of every result when i used $.get(), although i used json_encode() server-side.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
rev .25761
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 bootstrap 模块化布局 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信