Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight jQuery UI autocomplete

I'm using the autocomplete function in jQuery UI 1.8.6. And I want to highlight matching results. But for some reason when I use a regex to add "strong" tags around the matching characters, the string is being escaped. So I see [strong]matching chars[/strong], instead of marked up text.

This is the javascript I'm currently using:

$("#autocompleteinputfield").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "someservice",
            type: "GET",
            dataType: "json",
            data: { filter: request.term, maxResults: 10 },
            success: function (data) {
                response($.map(data, function (item) {
                    // return { label: item.ID + ' - ' + item.Name, id: item.ID, value: item.Name }
                    var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/ ([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/ gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi");

                    return {
                        label: (item.ID + ' - ' + item.Name).replace(regex, "<strong>$1</strong>"),
                        id: item.ID,
                        value: item.Name
                    }

                }))
            }
        });
    },
    select: function (event, ui) {
        alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
            : "Nothing selected, input was " + this.value);
    }
});

Update :

"Input" is the text entered in a textbox (in this case : [input type="text" id="autocompleteinputfield" /]

Output looks like this:

[{"Description":"Nothing meaningful","ID":3,"Name":"Joe Public‎"}]
like image 548
Saab Avatar asked Nov 05 '10 15:11

Saab


2 Answers

The jQuery autocomplete source code is the culprit. If you look in the actual javascript files, you'll find this definition for displaying items in the autocomplete list:

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( $( "<a></a>" ).text( item.label ) )
        .appendTo( ul );
}

You'll see it's appending ".text(item.label)" which causes the html to be escaped. To solve this, you kind of have to put in a hack to override this "_renderItem" method, replacing the line that appends the label as plain text with a line that appends the label as html. So update your code like this:

$(function () {
    $("#autocompleteinputfield").autocomplete({
        // leave your code inside here exactly like it was
    })
    .data('autocomplete')._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( '<a>' + item.label + '</a>' )
            .appendTo( ul );
    };
});

Update: With version >=1.10 of jQuery, there are some small modifications:

$(function () {
    $("#autocompleteinputfield").autocomplete({
        // leave your code inside here exactly like it was
    })
    .data('ui-autocomplete')._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "ui-autocomplete-item", item )
            .append( '<a>' + item.label + '</a>' )
            .appendTo( ul );
    };
});
like image 164
Ben Lee Avatar answered Sep 28 '22 09:09

Ben Lee


$.extend($.ui.autocomplete.prototype, {
    _renderItem: function (ul, item) {
        var searchMask = this.element.val();
        var regEx = new RegExp(searchMask, "ig");
        var replaceMask = "<b style=\"color:green;\">$&</b>";
        var html = item.label.replace(regEx, replaceMask);

        return $("<li></li>")
            .data("item.autocomplete", item)
            .append($("<a></a>").html(html))
            .appendTo(ul);
    }
});
like image 24
user3460922 Avatar answered Sep 28 '22 09:09

user3460922