Search code examples
jquerytextautocompletehighlightdiacritics

Unresponsive Script (JS-jQuery Autocomplete)


I'm working with jQuery Autocomplete and I'm kinda stuck on this one particular issue. My autocomplete source list isn't a simple arraylist, It stores database fields. I've replicated the functionality in this JSFiddle.

To elaborate, in autocomplete source, I have 3 fields :

  • item ID

  • A simple label, which contains diacritic characters - Ex: 'Dõctõr Smíth' (displayed as autocomplete menu item).

  • alternateText Ex: 'Doctor Smith' (converted string where diacritics are replaced with their non diacritic charater equivalent)

One of the requirements is to highlight every matched character, I've done so by overriding _renderItem function defined in jQueryUI.

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
    var splitTerm = this.term.split(' ').join('|');
    var re = new RegExp("(" + splitTerm + ")", "gi");        
    var text = item.label.replace(re, '<b>$1</b>');
    return $("<li></li>").data("item.autocomplete", item).append("<a>" + text + "</a>").appendTo(ul);
};

This works great if I have no alternateText field and only label is matched against the user input. But I want to be able to match user input with alternateText and highlight corresponding label characters. So i've further extended the _renderItem function to :

$.ui.autocomplete.prototype._renderItem = function( ul, item){  
    var splitTerm = this.term.split(' ').join('|');
    var re = new RegExp("(" + splitTerm + ")", "gi") ;      
    var arr,originalLabel= [];
    while ((arr = re.exec(item.alternateText)) != null) {
        originalLabel.push(item.label.substr(arr.index, (RegExp.$1.length)));        
    }
    var reg = new RegExp('(' + originalLabel.join('|') + ')', 'gi');
    var text = item.label.replace(reg, '<b>$1</b>');
    return $( "<li></li>" ).data( "item.autocomplete", item ).append( "<a>" + text + "</a>" ).appendTo( ul );
};

It takes matches from the alternateText and uses their indexes to highlight the text in the label field.

This works until I hit space bar. Script becomes unresponsive and I can't figure out whats causing it to act this way. Please help as I've exhausted all my resources and i'm still unable to find out the reason for this behavior.

Thanks in advance.

Additional Reference(s): https://github.com/JamieAppleseed/selectToAutocomplete


Solution

  • Your while loop in your $.ui.autocomplete.prototype._renderItem goes into an infinite loop. I am looking into its cause now.

    Edit: I think i identified the problem.

    The space was being added into end of regex as empty string, which cause the while to be always true.

    Check updated fiddle: http://jsfiddle.net/e14kne1s/36/