thatryan
thatryan

Reputation: 1559

How to get jQuery UI Autocomplete to ignore HTML entities

Trying to get jQuery UI Autocomplete to work with data labels that may have entities in them, such as a hyphen ( - ).

I extended the function so that what shows in the suggestion list works and shows the character instead of the entity code, but cannot figure out how to make it do the same when the item is chosen and it populates the text field.

(function( $ ) {
    $(function() {
        var url = SQMSAutocomplete.url + "?action=sqms_auto_search";
        $( "#sqms-auto-search" ).autocomplete({
            source: url,
            delay: 500,
            minLength: 3,

            select: function(event, ui){
               console.log(ui.item.link)
                // window.location = ui.item.url
             }
        })
        .autocomplete( "instance" )._renderItem = function( ul, item ) {
            return $( "<li>" )
              .append( item.label )
              .appendTo( ul );
          };
    });

})( jQuery );

Does that make sense?

Thank you

Upvotes: 1

Views: 1830

Answers (2)

John S
John S

Reputation: 21482

You could decode the entities in the labels by using a function for the source option. That should take care of both issues. That is, you wouldn't have to override the ._renderItem() function in that case.

$("#sqms-auto-search").autocomplete({
    source: function(request, response) {
        $.getJSON(url, { term: request.term }, function(items) {
            response($.map(items, function(item) {
                return $('<span></span>').html(item.label).text();
            });
        });
    },
    delay: 500,
    minLength: 3
});

jsfiddle

Upvotes: 1

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You should be able to accomplish this by decoding the HTML entities before assigning the value of the <input /> to the desired string.

Here's a simple example:

select: function (event, ui) {
    event.preventDefault();

    this.value = $('<div />').html(ui.item.label).text();
}

All credit for decoding HTML entities with JavaScript goes to this answer. Be aware of the usual disclaimers about decoding HTML entities this way: you are opening yourself up to possible XSS vulnerabilities.

The "gotcha" here is that you must prevent the default action of the select event, which is to put the label or value inside of the input. Here we're overriding that behavior and decoding the text first.

Example: http://jsfiddle.net/822fbwef/

Upvotes: 4

Related Questions