KO jqAuto
Custom Jquery Autocomplete with Knockout binding.
by RaviMakwana
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<div id="panel1">
<input id="ainput" class="form-control" data-bind="jqAuto: actualValue, jqAutoOnChange: autoChange, jqAutoQuery: $root.autoQuery, jqAutoSourceLabel: 'Description', jqAutoSourceInputValue: 'Name', jqAutoSourceValue: 'Id'" />
<label data-bind="text:actualValue"></label>
</div>
JavaScript
var data= [
{Id: 1, Name: 'T1', Description: 'test 1' },
{Id: 2, Name: 'T2', Description: 'test 2'},
{Id: 3, Name: 'T3', Description: 'test 3'},
{Id: 4, Name: 'T3.1', Description: 'test 3.1'},
];
function ViewModel(){
var self = this;
self.actualValue = ko.observable();
self.autoQuery = function (request, reponse) {
reponse(data.filter(x=>x.Name.indexOf(request.term) != -1));
/*CommonService.getAutoCompleteList("CityName", request.term, (res) => {
reponse(res.Data);
}, (err) => {
console.log(err);
});*/
};
self.autoChange = function (ui, event) {
/* if (ui.item) {
} else {
$("#ainput").val('');
$("#ainput").focus();
}*/
}
return self;
}
$(document).ready(function(){
var data = new ViewModel();
var elem = $('#panel1')[0];
ko.applyBindings(data, elem);
});
//jqAuto -- main binding (should contain additional options to pass to autocomplete)
//jqAutoSource -- the array to populate with choices (needs to be an observableArray)
//jqAutoQuery -- function to return choices
//jqAutoValue -- where to write the selected value
//jqAutoSourceLabel -- the property that should be displayed in the possible choices
//jqAutoSourceInputValue -- the property that should be displayed in the input box
//jqAutoSourceValue -- the property to use for the value
ko.bindingHandlers.jqAuto = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var options = {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = valueAccessor(),
source = allBindings.jqAutoSource || ko.observableArray(),
query = allBindings.jqAutoQuery,
valueProp = allBindings.jqAutoSourceValue || "Id",
jqAutoOnChange = allBindings.jqAutoOnChange,
inputValueProp =...