0

I want to highlight matched characters in jquery autocomplete.

If i type GC,it give me below,which is OK

Green Community

Now i want G and C both to be bold/strong.

$('#9').autocomplete({
    source: "auto_loc_name.php",
    selectFirst: true, 
         minLength: 0,
    select: function (event, ui) {
        alert(ui.item.value);
    }
});
  • Since you haven't specified how you match your search term, we can't help you with the replacement pattern. Does GC match any name with a G and a C in it? Case sensitive? Some other pattern? This should get you started though http://stackoverflow.com/questions/2435964/jqueryui-how-can-i-custom-format-the-autocomplete-plug-in-results – user2261892 Jun 27 '13 at 11:58
  • @user2261892:This is not case sensitive...my matched pattern is it always matched first letter..like if i type GC it give me Green Color –  Jun 27 '13 at 12:03
  • i tried this code "$.ui.autocomplete.prototype._renderItem " but it only works for first word –  Jun 27 '13 at 12:34

2 Answers2

0

You can try something like this, based on code from jQueryUI: how can I custom-format the Autocomplete plug-in results?

function monkeyPatchAutocomplete() {

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
    var matchstring = [];
    $.each(this.term.split(""), function(index, c){         
         matchstring.push("^"+c+"|\b"+c);
    });

    var output = item.label.replace(new RegExp("(" + matchstring.join("|") + ")", "gi"), '<span class="ui-menu-item-highlight">$1</span>');

    return $("<li>")
        .append($("<a>").html(output))
        .appendTo(ul);
};
}

$(function () {
    monkeyPatchAutocomplete();
});

May or may not work. The idea is to get a Regex string like ^G|\bG for each character. I'm sure this misses quite a few cases, so keep working on it.

Edit: working jFiddle. http://jsfiddle.net/9MC5M/ Like the code above but with a few bug fixes. The search is deliberatly broken, it just returns all items to showcase the highlighting.

Community
  • 1
  • 1
user2261892
  • 188
  • 7
  • I'm 100% sure you haven't tried this before, because I wrote a large part of it just now, it's just based on another piece of code. The interesting part is the regex match. There is no built in highlighter for jQuery autocomplete – user2261892 Jun 27 '13 at 13:27
  • this is doing for one character as all others is doing...do not match my requirements –  Jun 27 '13 at 13:46
  • No it is not. YOu are just looking at the _renderItem part... That tells autocomplete what to do when creating a menu item in the menu that appears. What this code does is: Splits your search string into each letter Creates a regex like ^G|\bG for each character in the search term, so if the term is GC, the match pattern is ^G|\bG|^C|\bC Does a global replace of the item label, like Green Community. Global means it replaces every occurence it finds. You might have to fiddle around with it still, but this shows you where to start. Your work is to find a regular expression that matches perfect. – user2261892 Jun 27 '13 at 13:49
  • my requirement is simple...if i type GC,i must get like this...Green Community –  Jun 27 '13 at 14:00
  • i have worked on it how to get this result on sql query..no one of autocomplete can do like this..neither of them can highlight like what i want –  Jun 27 '13 at 14:01
  • Here's a working JFiddle.It's basically the code from above, but fixed up a bit: http://jsfiddle.net/9MC5M/ Note that the search doesn't actually work, it just returns all results regardless, it's just to show the highlighting in work. Type in GC. – user2261892 Jun 27 '13 at 14:09
0

I was using JQuery Autocomplete as a combobox and your needs work well with me and you can review the following code may be help you :

(function( $ ) {
            $.widget( "ui.combobox", {
                _create: function() {
                    var input,
                    self = this,
                    select = this.element.hide(),
                    selected = select.children( ":selected" ),
                    value = selected.val() ? selected.text() : "",
                    wrapper = $( "<span>" )
                    .addClass( "ui-combobox" )
                    .insertAfter( select );

                    input = $( "<input>" )
                    .appendTo( wrapper )
                    .val( value )
                    .addClass( "ui-state-default" )
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: function( request, response ) {
                            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                            response( select.children( "option" ).map(function() {
                                var text = $( this ).text();
                                if ( this.value && ( !request.term || matcher.test(text) ) )
                                    return {
                                        label: text.replace(
                                        new RegExp(
                                        "(?![^&;]+;)(?!<[^<>]*)(" +
                                            $.ui.autocomplete.escapeRegex(request.term) +
                                            ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>" ),
                                        value: text,
                                        option: this
                                    };
                            }) );
                        },
                        select: function( event, ui ) {
                            ui.item.option.selected = true;
                            self._trigger( "selected", event, {
                                item: ui.item.option
                            });
                        },
                        change: function( event, ui ) {
                            if ( !ui.item ) {
                                var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                                valid = false;
                                select.children( "option" ).each(function() {
                                    if ( $( this ).text().match( matcher ) ) {
                                       this.selected = valid = true;
                                        return false;
                                    }
                                });
                                if ( !valid ) {
                                    // remove invalid value, as it didn't match anything
                                    $( this ).val( "" );
                                    select.val( "" );
                                    input.data( "autocomplete" ).term = "";
                                    return false;
                                }
                            }
                        }
                    })
                    .addClass( "ui-widget ui-widget-content ui-corner-left" );

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

                    $( "<a>" )
                    .attr( "tabIndex", -1 )
                    .attr( "title", "Show All Items" )
                    .appendTo( wrapper )
                    .button({
                        icons: {
                            primary: "ui-icon-triangle-1-s"
                        },
                        text: false
                    })
                    .removeClass( "ui-corner-all" )
                    .addClass( "ui-corner-right ui-button-icon" )
                    .click(function() {
                        // close if already visible
                        if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                            input.autocomplete( "close" );
                            return;
                        }

                        // work around a bug (likely same cause as #5265)
                        $( this ).blur();

                        // pass empty string as value to search for, displaying all results
                        input.autocomplete( "search", "" );
                        input.focus();
                   });
                }

            });
        })( jQuery );

and I think your needs in the following part but I don't know how to use that in your code :

source: function( request, response ) {
                            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                            response( select.children( "option" ).map(function() {
                                var text = $( this ).text();
                                if ( this.value && ( !request.term || matcher.test(text) ) )
                                    return {
                                        label: text.replace(
                                        new RegExp(
                                        "(?![^&;]+;)(?!<[^<>]*)(" +
                                            $.ui.autocomplete.escapeRegex(request.term) +
                                            ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>" ),
                                        value: text,
                                        option: this
                                    };
                            }) );
                        },
Ahmed Atta
  • 363
  • 1
  • 7