1

I am using jQuery UI v1.9. I successfully implemented the jQuery UI Autocomplete widget but I have some trouble when I have to handle cases when a user doesn't select any item from the open menu but still continue to type letters in the related autocomplete field (that is, cases when the user continues to type letters even if the autocomplete menu is hidden because no item with the name as the entered one is present in that menu).

In such cases (when no item selection was performed but a string is present in the autocomplete field), I would like to alert the user that he / she is no selecting an existing object but that he / she is typing a custom one. How can I make that?


Note: Practically speaking, I am trying to force the user to select an existing item or, if that was not selected, to prompt he / she to create a new one.

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

2

You can set a callback function for the change event of autocomplete plugin where you should be able to check if an item has been selected:

$( "#autocomplete" ).autocomplete({
     change: function(e,ui){
         if(ui.item === null)
           alert('No item has been selected')  
    }
});

UPDATE:

If you want to trigger change event before input loses focus, you could use following code, triggering it on keypress event:

$( "#autocomplete" ).autocomplete({
         change: function(e,ui){
             if(!ui || ui.item === null)
                 console.log('No item has been selected') 
        }
    }).on('keypress',function(){$(this).autocomplete('option','change').call()});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Your code seems to work as expected, but what I can do in order to make that to be more "responsive"? That is (maybe by using some jQuery UI features), how can I check the `null` condition in "real-time" and accordingly trigger the alert? – Backo Nov 19 '12 at 19:23
  • I get the idea but I opened a [new question](http://stackoverflow.com/questions/13476146/is-it-possible-to-trigger-bind-a-jquery-ui-event) since I have some related troubles. – Backo Nov 20 '12 at 15:12