Wednesday, March 21, 2012

Knockout JS AutoComplete Binding with multiple selections

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

    ko.bindingHandlers.autocomplete_multiselect = {
        init: function (element, params) {
            var options = params().split(' ');
            $(element).bind("focus", function () {
                $(element).change();
            });
            $(element).autocomplete({ source: function (request, response) {
                $.getJSON(options[0], { q: extractLast(request.term) }, function (data) {
                    response($.map(data, function (item) {
                        return { label: item[options[1]], value: item[options[2]] };
                    }));
                });
            },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    var terms = split(this.value);
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push(ui.item.value);
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            })
        .bind("focus", function () {
            $(element).change();
        });
        },
        update: function (element, params) {
        }
    };


Use it in the following way;
<input type="text" data-bind="value: Categories, autocomplete_multiselect: '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.



2 comments:

  1. Thanks for the great examples! You should use jsFiddle.com and create Fiddles for these. Thx!

    ReplyDelete