Can't clear autocomplete value selected in knockout

I am using knockout-jqautocomplete plugin in one of my projects. Whenever I select a value in autocomplete, I check if another array that I maintain has a value. If so, I don't do anything, otherwise I add the selected value to the array. As soon as I click / select a value, the selected value will be filled in the autocomplete text box. But I don't want that to happen.

Once I click on it, I just need to call the function I want to check if it exists or not and clear the auto-completion value. But for some reason, I am unable to clear the autocomplete value.

Please find the jsfiddle link below.

http://jsfiddle.net/kumarr/qy0dkbdp/2/

Would be grateful for the help

var ViewModel = function() {
var self = this;
this.templateValue = ko.observable();

this.remoteData = ko.observableArray([{
        id: 1,
        name: "one",
        description: "one description"
    },
    {
        id: 2,
        name: "two",
        description: "two description"
    },
    {
        id: 3,
        name: "three",
        description: "three description"
    }]);


this.ownerList = ko.observableArray([]);






this.addOwners = function (owner) {
    var exists = false;


        for (var o in self.ownerList()) {
            var temp = self.ownerList()[o];
            if (temp.id === owner.id) {
                exists = true;
            }
        }

        if (exists === false) {
            self.ownerList.push({
                "id": owner.id,
                "name": owner.name
            });
        }
        self.templateValue('');        


}

};


ko.applyBindings(new ViewModel());

      

my html

<input data-bind="jqAuto: { source: remoteData, value: templateValue, inputProp: 'name', template: 'itemTmpl'  }" />

<div data-bind="foreach:ownerList">
  <div data-bind="text:name">
  </div>
</div>


<script id="itemTmpl" type="text/html">
  <a>
    <strong data-bind="text: id,click:$root.addOwners"></strong>
    <em data-bind="text: name,click:$root.addOwners"></em>
  </a>
</script>

      

+3


source to share


1 answer


Instead of adding the binding click

in your template, I think the approach that might work better for you in this scenario is to subscribe to the templateValue

observable. Whenever it is updated, you can run your logic, click on your observable array if necessary, and finally clear the value.

You have configured your subscription as:



this.templateValue.subscribe(this.addOwners);

      

Here's a slightly modified version of your fiddle: http://jsfiddle.net/rniemeyer/brpd63r8/

+3


source







All Articles