Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery UI autocomplete - Hide list after hiting enter

I have an input. I use the Jquery UI autocomplete to propose suggestions to the user. Lets image I have in my list 3 items: item1, item2, item3. What I am looking for is the list to be closed when the user hits enter. For instance if the user only enters "it", all 3 elements will be displayed. In that case if he hits enter I would like the list to be closed. I do not manage to comue up with a solution for that. Hope someone can help. Cheers. Marc.

http://jsfiddle.net/vXMDR/

My html:

<input id="search" type="input" />​

My js:

$(function() {

    var availableTags = [
            "item1","item2","item3"
        ];

    $("#search").autocomplete({
        source:availableTags,
        minLength: 0
        });
});​
like image 812
Marc Avatar asked Mar 07 '12 13:03

Marc


2 Answers

Here is the solution: http://jsfiddle.net/vXMDR/3/

Let me know if you have questions.

The magic is binding the autocomplete close method to keypress

 $("#search").keypress(function(e){ 
    if (!e) e = window.event;   
    if (e.keyCode == '13'){
      $('#search').autocomplete('close');
      return false;
    }
  });

UPDATE

$("#search").keypress(function(e){ binds keypress of the #search element to the function specified, passing in the event object. You could also write this as $("#search").on('keypress', function(e) {...

if (!e) e = window.event; ensures that if a valid event was not passed in, it sets e to the current window.event object.

Finally, if (e.keyCode == '13'){ tests that event keycode value is equal to the 'enter' key. For a list of valid keycodes, see here.

Here is the documentation for autocomplete close method - http://docs.jquery.com/UI/Autocomplete#method-close

like image 99
shanabus Avatar answered Oct 20 '22 14:10

shanabus


$(function() {

    var availableTags = [
            "item1","item2","item3"
        ];

    $("#search").autocomplete({
        source:availableTags,
        minLength: 0
    }).keyup(function (e) {
        if(e.which === 13) {
            $(".ui-menu-item").hide();
        }            
    });
});​

http://jsfiddle.net/vXMDR/2/

like image 26
karim79 Avatar answered Oct 20 '22 15:10

karim79