Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Autocomplete behaviour. How to search free text on enter?

first question (and hopefully, but doubtfully my only one)

I'm using the jQuery UI Autocomplete. Here is sample code to replicate my issue.

var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];

$("#autocomplete").autocomplete({
    source: suggestions
});

When a user types 'J' they will be presented with 'Clojure' and 'JavaScript' as suggestions.

I have omitted Java from this list, if the user wants to search for Java, they type 'Java', press the enter key but the form does not submit. If you add a space the 'JavaScript' suggestion disappears and the form can be submitted by pressing the enter key.

I am creating a free search, I want users to be able to search by pressing enter even if there are suggestions available.

$("#autocomplete").keypress(function(event) {
  alert(event.keyCode);
  if (event.keyCode=='13') $this.closest('form').submit();
});

I tried the above thinking I could manually detect a submit keypress and submit the form, but the alert shows all keys are detected EXCEPT submit which seems to be suppressed by the autocomplete.

Any help is greatly appreciated! Thanks.

like image 365
John Avatar asked Sep 24 '10 10:09

John


1 Answers

UPDATE

I had to make a few changes, but this code works fine on my side after doing that. First, e.keycode should be e.keyCode. I didn't think the case mattered, but it does. Also, make sure you are not quoting the 13 when you check for the keyCode to be the enter button. It will not work correctly if you do so. Here's the new code:

var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
    source: suggestions
}).keypress(function(e) {
    if (e.keyCode === 13) {
        $(this).closest('form').trigger('submit');
    }
});

The keypress function should look like below, and also, you can chain the autocomplete and keypress functions to make it easier on you. Below code should work.

var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
    source: suggestions
}).keypress(function(e) {
    if (e.keycode === 13) {
        $(this).closest('form').trigger('submit');
    }
});
like image 139
ryanulit Avatar answered Sep 23 '22 06:09

ryanulit