raul
raul

Reputation: 1269

Issues with jQuery UI autocomplete

I wrote the following code that uses jQuery UI's autocomplete method on a text box.

$(function() {
    $('#project').autocomplete({
            source: function(request, response){response(Object.getOwnPropertyNames(projects))},
            minLength: 0,
            messages: {noResults: '', results: function(){}},
            autoFocus: true
        }).on('focus', function(event) { //Display the suggestions list on focus
            $(this).autocomplete("search", "");
        });
})

I'm facing the following issues:

  1. While clicking on a text field does show the corresponding list of suggestions, the autoFocus doesn't work. I want the first value in the list to be highlighted. But this is all I get:enter image description here
  2. On mouse-over, the list elements get highlighted, like so:

    enter image description here

    I use the following styling to accomplish this:

    .ui-autocomplete a:hover {background-color: #C1CDCD;cursor:default}
    

    But, when I use the up/down arrows to navigate the list, the corresponding value shows in the text field but the element in the list doesn't get highlighted.

How do I resolve these issues?

Here's the JSFiddel.

Thanks for your time.

Upvotes: 1

Views: 456

Answers (1)

Rooster
Rooster

Reputation: 10077

You can accomplish what you want by utilizing the open and focus methods, then turning the autofocus off so it doesn't unhighlight the first item. I also utilized a class called first open to allow the first item to be highlighted again if it initially loses focus.

code:

JS FIDDLE

codez:

projects = {Apple: "fruit",Apostle: "Saint"};
$(function () {
    $('#project').autocomplete({
        source: function (request, response) {
            response(Object.getOwnPropertyNames(projects));
        },
        minLength: 0,
        messages: {
            noResults: '',
            results: function () {}
        },
        //autoFocus: true,
        open: function( event, ui ) {
                $('.ui-autocomplete > li:first-child a').addClass('ui-state-focus first_open');
        },
        focus: function( event, ui ) {            
            if(ui.item.value != $('.ui-state-focus').text()){
                $('.first_open').removeClass('ui-state-focus first_open');
            }

       },    
    }).on('focus', function (event) { //Display the suggestions list on focus   
        $(this).autocomplete("search", "");

    });
});

Upvotes: 1

Related Questions