TYPEAHEAD.JS
Use .data() instead of .attr() for values of items in the typeahead -- most AJAX calls return an array of JSON objects. This change would not affect the existing way the typeahead works (e.g. using an array of strings would still work just fine).
by B
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.0/bootstrap.min.js"></script>
<script src="https://dl.dropbox.com/s/6li2p3qgnebu8gy/bootstrap-typeahead.js"></script>
<h5>Old way with just an array of strings:</h5>
<input type="text" class="test-data-input" placeholder="Type 'A'" autocomplete=off>
<label class="test-attr-val"></label><br/>
CSS
<style>
input {
border:1px solid #cccccc;
border-radius: 3px 3px 3px 3px;
width: 370px;
padding: 9px 9px 9px 9px;
margin: 3px 0px 3px 3px;
color: #e1e1e1;
}
input:focus {
border-color:#00cc33;
box-shadow:0 0 10px #d5d5d9;
-webkit-box-shadow:outset 0 1px 9px #d5d5d9;
-moz-box-shadow:outset 0 1px 9px #d5d5d9;
color: #676767;
}
/* min Jquery CSS elements for autocomplete */
.ui-autocomplete { position: absolute; cursor: default; }
.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; float: left; background-color:#f9f9f9; border: 1px solid #efefef; border-radius: 3px 3px 3px 3px; }
.ui-menu .ui-menu {
margin-top: -3px;
}
.ui-menu .ui-menu-item {
margin:0;
padding: 0;
zoom: 1;
float: left;
clear: left;
width: 100%;
font-family:arial;
}
.ui-menu .ui-menu-item a {
text-decoration:none;
display:block;
padding:.1em .3em;
line-height:1.5;
zoom:1;
}
.ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active {
font-weight: bold;
}
</style>
JavaScript
$('.test-attr-input').typeahead({
source: [
'Alaska',
'Alabama',
'Illinois'
]
// there would be no need to change this function; it is overridden just to show the value difference from the other typeahead
, updater: function (item) {
$('.test-attr-val').text('Value: '+item);
return item
}
});
$('.test-data-input').typeahead({
source: [{
display: 'Alaska',
val: 'AK'
},{
display: 'Alabama',
val: 'AL'
},{
display: 'Arkansas',
val: 'AK'
},{
display: 'Illinois',
val: 'IL'
}]
, updater: function (item) {
$('.test-data-val').text('Value: '+item.val);
return item.display
}
, highlighter: function(item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.display.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
}
, matcher: function(item) {
return ~item.display.toLowerCase().indexOf(this.query.toLowerCase())
}
, sorter: function(items) {
return items
}
});