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
        });
});
                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
$(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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With