How can i show a blank option in jquery autocomplete?

Viewed 10300

I am using a jquery autocomplete with combobox nabled. I want to show an empty option however whenever I set the value of my initial selection to an empty string it is not shown in the combobox.

The item is present it just contains no height.

Is it possible to have a blank option on an autocomplete combobox ?

6 Answers
$("#ctrl").autocomplete({
    source: [ "\u00A0", "One", "Two" ]
});

You can extend the autocomplete widget like this:

$.widget( "ui.autocomplete", $.ui.autocomplete, {
    _renderMenu: function (ul, items) {
        var that = this;

        // add a blank item
        if (this.options.blankItem) {
            var blank = [{
                id: "",
                label: "<none>",
                value: ""
            }];
            items = blank.concat(items);
        }

        $.each(items, function (index, item) {
            var rendered = that._renderItemData(ul, item);

            // ensure min height on blank item. hmm, maybe a class would be better...
            if (index === 0 && that.options.blankItem) {
                $(rendered).find('div').css('minHeight', '30px');
            }
        });
    }
});

And then use it like this:

$( "#textbox" ).autocomplete({
        source: contactNames,
        blankItem: true
    })

Here's a Fiddle for that.

If you prefer not to extend the widget for some reason, you can add the function to the change method like this:

$( "#textbox" ).autocomplete({
    create: function(){
        $(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
            [ _renderMenu function contents... ]
        }
    }
})
Related