meridius
meridius

Reputation: 1587

jQuery autocomplete combobox with searchable label AND description of option

I'd like to use multirow autocomplete combobox from jQuery UI but with searchable both label and description of options. Or label and value, but value would had to be visible for user.

Is there any way to do it?

Update: Also button (down arrow) to display (perhaps scrollable) list of all the options would be nice.

Upvotes: 3

Views: 2862

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

This is definitely doable. Adapting the answer you linked to, here's how you would search by the desc property of each item, as well as the label property. This examples also incorporates a jQueryUI button (#showall) that shows all items.

JavaScript:

$(function() {
    var projects = [ /* ... */ ];

    $("#showall").button({
        icons: {
            primary: "ui-icon-triangle-1-s"
        },
        text: false
    })
        .removeClass("ui-corner-all")
        .addClass("ui-corner-right ui-combobox-toggle")
        .on("click", function () {
            $("#project").autocomplete("search", "");
        });


    $("#project").autocomplete({
        minLength: 0,
        source: function(request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            /* Search by description or label: */
            response($.grep(projects, function(value) {
                return matcher.test(value.label || value.value || value) || 
                    matcher.test(value.desc);
            }));
        },
        focus: function(event, ui) {
            $("#project").val(ui.item.label);
            return false;
        },
        select: function(event, ui) {
            $("#project").val(ui.item.label);
            $("#project-id").val(ui.item.value);
            $("#project-description").html(ui.item.desc);
            $("#project-icon").attr("src", "images/" + ui.item.icon);

            return false;
        }
    }).data("autocomplete")._renderItem = function(ul, item) {
        return $("<li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "<br>" + item.desc + "</a>").appendTo(ul);
    };
});​

HTML:

<div class="ui-widget">
    <label>Your preferred programming language:</label>
    <span class="ui-combobox">
        <input id="project" type="text" class="ui-combobox-input ui-state-default ui-widget ui-widget-content ui-corner-left" /><a id="showall" tabindex="-1" title="Show All Items"></a>
    </span>
</div>​

Example: http://jsfiddle.net/J5rVP/4/

Try searching for "CSS" or "interface"

Upvotes: 4

Related Questions