Wednesday, March 21, 2012

Knockout JS AutoComplete Binding

The following custom binding can be used to bind data to the jQuery UI autocomplete widget;

    ko.bindingHandlers.autocomplete = {
        init: function (element, params) {
            var options = params().split(' ');
            $(element).bind("focus", function () {
                $(element).change();
            });
            $(element).autocomplete({ source: function (request, response) {
                $.getJSON(options[0], { q: request.term }, function (data) {
                    response($.map(data, function (item) {
                        return { label: item[options[1]], value: item[options[2]] };
                    }));
                });
            }
            });
        },
        update: function (element, params) {
        }
    };

Use it in the following way;
<input type="text" data-bind="value: Category, autocomplete: 'AutoCompleteDataSourceUrl ItemName ItemValue'" />
Where AutoCompleteDataSourceUrl should be replaced by the URL of the service returning autocomplete data. ItemName and ItemValue should be replaced by the names of the name and value fields in the returned json.

4 comments:

  1. is this the right sintaks for input type?

    "input class='validate[required]' data-bind="value: name, uniqueName: true, $root.autocomplete: 'http://localhost/b_accounting/index.php?r=/CProduct/CProductAutoComplete value label'" /"

    but this is not work...:-(

    ReplyDelete
  2. Thank you for sharing this works great. Exactly what I was looking for.

    ReplyDelete
  3. I added the binding of the focusout event because sometimes focus did not catch all of the changes.

    ReplyDelete
    Replies
    1. Hi Aaron... can u send me the sample code with binding json into observable array

      Delete