Does any one know the best way to create an autocomplete combobox with Knockout JS templates?
I have the following template:
<script type="text/html" id="row-template">
<tr>
...
<td>
<select class="list" data-bind="options: SomeViewModelArray,
value: SelectedItem">
</select>
</td>
...
<tr>
</script>
Sometimes this list is long and I'd like to have Knockout play nicely with perhaps jQuery autocomplete or some straight JavaScript code, but have had little success.
In addition, jQuery.Autocomplete requires an input field. Any ideas?
Niemeyer's solution is great, however I run into an issue when trying to use autocomplete inside a modal. Autocomplete was destroyed on modal close event (Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'option' ) I fixed it by adding two lines to the binding's subscribe method:
Fixed the clearing of input on load problem for RP's Solution. Even though it's kind of an indirect solution, I changed this at the end of the function:
to this:
Here is a jQuery UI Autocomplete binding that I wrote. It is intended to mirror the
options
,optionsText
,optionsValue
,value
binding paradigm used with select elements with a couple of additions (you can query for options via AJAX and you can differentiate what is displayed in the input box vs. what is displayed in the selection box that pops up.You do not need to provide all of the options. It will choose defaults for you.
Here is a sample without the AJAX functionality: http://jsfiddle.net/rniemeyer/YNCTY/
Here is the same sample with a button that makes it behave more like a combo box: http://jsfiddle.net/rniemeyer/PPsRC/
Here is a sample with the options retrieved via AJAX: http://jsfiddle.net/rniemeyer/MJQ6g/
You would use it like:
UPDATE: I am maintaining a version of this binding here: https://github.com/rniemeyer/knockout-jqAutocomplete