<!DOCTYPE HTML>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet" />
</head>
<body>
<br/>
<div class="container">
<div class="row">
<div class="span12">
<form>
<input
type="text"
class="span6 typeahead"
placeholder="Who was your favorite James Bond?"
autocomplete="off"
data-provide="typeahead"
/>
<br/>
<input type="text" class="span1" name="bondId" id="bondId" value="" />
</form>
</div>
</div>
<div class="row">
<div class="span6">
<p>
In this example I'll ask you to suspend your disbelief momentarily: Pretend that the second text input is
actually a hidden form field. Functionally they are equivalent, the only difference is that you can see the
textbox, making it better for demonstration purposes.
</p>
<p>
Visually, this example is the same as the last one; the user selects their favorite Bond by name. But under
the hood, we're saving the selected Bond Id so that we don't have to look it up after submission. The name
would be included in the form post, too, but you can just ignore that.
</p>
</div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<script src="//underscorejs.org/underscore-min.js"></script>
<script type="text/javascript">
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: 'bonds.json'
,cache: false
,success: function(data){
//reset these containers every time the user searches
//because we're potentially getting entirely different results from the api
bondObjs = {};
bondNames = [];
//Using underscore.js for a functional approach at looping over the returned data.
_.each( data, function(item, ix, list){
//for each iteration of this loop the "item" argument contains
//1 bond object from the array in our json, such as:
// { "id":7, "name":"Pierce Brosnan" }
//add the label to the display array
bondNames.push( item.name );
//also store a hashmap so that when bootstrap gives us the selected
//name we can map that back to an id value
bondObjs[ item.name ] = item.id;
});
//send the array of results to bootstrap for display
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
//save the id value into the hidden field
$( "#bondId" ).val( bondObjs[ selectedName ] );
//return the string you want to go into the textbox (the name)
return selectedName;
}
});
});
</script>
</body>
</html>
[
{ "id":1, "name":"Barry Nelson" }
,{ "id":2, "name":"David Niven" }
,{ "id":3, "name":"Sean Connery" }
,{ "id":4, "name":"George Lazenby" }
,{ "id":5, "name":"Roger Moore" }
,{ "id":6, "name":"Timothy Dalton" }
,{ "id":7, "name":"Pierce Brosnan" }
,{ "id":8, "name":"Daniel Craig" }
]