jquery autocomplete highlighting jquery autocomplete highlighting jquery jquery

jquery autocomplete highlighting


Thanks goes to David Murdoch at http://www.vervestudios.co/ for providing this useful answer:

$.ui.autocomplete.prototype._renderItem = function( ul, item){  var term = this.term.split(' ').join('|');  var re = new RegExp("(" + term + ")", "gi") ;  var t = item.label.replace(re,"<b>$1</b>");  return $( "<li></li>" )     .data( "item.autocomplete", item )     .append( "<a>" + t + "</a>" )     .appendTo( ul );};$("#keyword").autocomplete({   source: "ajax/autocomplete.php?action=keyword",   minLength: 2 });


Thought somone might find this useful. it's a complete HTML doc that makes uses of the above principles. I used it as a protoype for some of my work.

    <html xmlns="http://www.w3.org/1999/xhtml">    <!--        orders.html simply returns the following text        Basketball#Football#Baseball#Helicopter#gubbins#harry potter#banyan    -->    <head id="Head1" runat="server">        <title>AutoComplete Box with jQuery</title>        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"            rel="stylesheet" type="text/css" />        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>        <script type="text/javascript">            function loadData() {                var sURL = "orders.htm";                $.ajaxSetup({ cache: false });                $.ui.autocomplete.prototype._renderItem = function (ul, item) {                    var term = this.term.split(' ').join('|');                    var re = new RegExp("(" + term + ")", "gi");                    var t = item.label.replace(re, "<b>$1</b>");                    return $("<li></li>")                    .data("item.autocomplete", item)                    .append("<a>" + t + "</a>")                    .appendTo(ul);                };                $.get(sURL, function (responseText) {                    data = responseText.split('#');                    $("#txtSearch").autocomplete({                        //source: availableSports                        source: data,                        minLength: 2                     });                });            }        </script>    </head>    <body>        <form id="form1" runat="server">        <div class="demo">            <div class="ui-widget">                <label for="tbAuto">                    Enter data:                </label>                <input type="text" id="txtSearch" class="autosuggest" onkeyup="loadData();" />            </div>        </form>    </body>    </html>

Hopefully it'll help someone as it helped me.