Rodrigo Boniatti
Rodrigo Boniatti

Reputation: 447

How to keep what was typed in autocomplete

I am using a Javascript autocomplete widget, which properly shows the suggestion list as I type, however when I press the down key to browse the list, my current input is erased.

enter image description here SERVIÇO OU PRODUTO is a placeholder.

While this is not my exact issue, this jsfiddle should demonstrate the problem. After typing a letter and pressing the down key, it replaces my input with the selection.

This is my code:

$.widget('custom.mcautocomplete', $.ui.autocomplete, {
    _create: function() {
        this._super();
    },
    _renderItem: function(ul, item) {
        var t = '',
            result = '';

        $.each(this.options.columns, function() {
            t = '<span>' + item[0] + ' - R$ ' + item[1] + '</span>';
        });

        result = $('<li></li>')
            .data(item)
            .append(t)
            .appendTo(ul);
        return result;
    }
});

$("#my-input").mcautocomplete({
    columns: my-columns,
    source: my-info,
    select: function(event, ui) {
        this.value = (ui.item[0]);
        return false;
    }
});

Upvotes: 0

Views: 209

Answers (1)

spenibus
spenibus

Reputation: 4409

You must cancel the focus event:

focus: function(event, ui) {
    event.preventDefault();
}

Working demo on jsfiddle

The jsfiddle you provided does cancel the event but then nullifies its own action right away by using this:

$("#customer-search").val(ui.item.label);

See Autocomplete Widget - event - focus

focus( event, ui )

Type: autocompletefocus

Triggered when focus is moved to an item (not selecting). The default action is to replace the text field's value with the value of the focused item, though only if the event was triggered by a keyboard interaction.

Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.

Code examples

Initialize the autocomplete with the focus callback specified:

$( ".selector" ).autocomplete({
    focus: function( event, ui ) {}
});

Bind an event listener to the autocompletefocus event:

$( ".selector" ).on( "autocompletefocus", function( event, ui ) {} );

Upvotes: 1

Related Questions