Knockout & Bootstrap typeahead
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<ol>
<li><strong>Steps to repro</strong></li>
<li>Type 'o' in the field below</li>
<li>You should get typeahead menu</li>
<li>Choose any of the items</li>
<li>The value in the input changes while the value in the model stays 'o'</li>
</ol>
<input type="text" data-bind="typeahead:availableProducts, value:productName" placeholder="Type o"/>
<div>
Value is: <span data-bind="text:productName" />
</div>
JavaScript
var sourceList = function() {
alert("Hello");
var jsonString = '{"suggestions":[{"text":"rock"},{"text":"rocks"}]}'
var jsonObj = $.parseJSON(jsonString);
alert(jsonObj[0]);
var jsobObj2 = $.parseJSON(jsonObj[0].suggestions);
var sourceArr = [];
for (var i=0; i<jsonObj2.length; i++) {
sourceArr.push(jsonObj2[i].text);
}
return sourceArr;
}
// Bind twitter typeahead
ko.bindingHandlers.typeahead = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var $element = $(element);
var allBindings = allBindingsAccessor();
$element.attr("autocomplete", "off")
.typeahead({
'source': sourceList,
'minLength': allBindings.minLength,
'items': allBindings.items,
'updater': allBindings.updater
});
}
};
function MyModel(){
var self = this;
self.productName = ko.observable();
self.availableProducts = ['One', 'Two', 'Three'];
}
ko.applyBindings(new MyModel());