How to highlight input words in autocomplete jquery ui

后端 未结 6 2183
后悔当初
后悔当初 2020-12-25 13:46

Could you please help me in highlighting the typed words in the auto complete text box. i am already populating the autocomplete words and i need to just highlight the typed

6条回答
  •  死守一世寂寞
    2020-12-25 14:32

    It seems to me you should overwrite the _renderItem method to have custom rendering of the items. The code could be about the following:

    $("#studentName").autocomplete({/* all your parameters*/})
        .data("autocomplete")._renderItem = function (ul, item) {
            var newText = String(item.value).replace(
                    new RegExp(this.term, "gi"),
                    "$&");
    
            return $("
  • ") .data("item.autocomplete", item) .append("
    " + newText + "
    ") .appendTo(ul); };

    In the code I use jQuery UI CSS "ui-state-highlight" for highlighting. You can use instead. Moreover I don't include the code which would escape any RegEx characters which could be inside of this.term. I wanted to explain you the main idea only. Look at the answer for example for additional information.

    UPDATED: More recent versions of jQuery UI uses .data("ui-autocomplete") instead of .data("autocomplete"). To make your code working in both (old and new) versions of jQuery you can do something like the following:

    var $elem = $("#studentName").autocomplete({/* all your parameters*/}),
        elemAutocomplete = $elem.data("ui-autocomplete") || $elem.data("autocomplete");
    if (elemAutocomplete) {
        elemAutocomplete._renderItem = function (ul, item) {
            var newText = String(item.value).replace(
                    new RegExp(this.term, "gi"),
                    "$&");
    
            return $("
  • ") .data("item.autocomplete", item) .append("
    " + newText + "
    ") .appendTo(ul); }; }

    UPDATED 2: In the same way the name "item.autocomplete" should be changed to "ui-autocomplete-item". See here.

提交回复
热议问题