Question

I have the following code for autocomplete :

$(function() {
    var availableTags = [
                " x",
                "y",
                "z",
                "l",
                "m",
                "n",
                "o",
              ];

    $( ".tags" ).autocomplete({
          source: availableTags,position: { my : "left+2 bottom-50" , of:".tags"}
    });
 });

It works fine but when I select the suggested text using up/down keys, the selected text is immediately replaced in the text field. Instead, I want it to be replaced only when ENTER is pressed on the selection. Any way to achieve this?

Was it helpful?

Solution

When suggestion elements are viewed (using arrows key too) is triggered the focus event, so you can simply prevent the default action using preventDefault method.

Quick reference on focus:

Triggered when focus is moved to an item (not selecting). The default action is to replace the text field's value with the value of the focused item, though only if the event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.

Code:

$(function () {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"];



    $("#tags").autocomplete({
        source: availableTags,
        position: {
            my: "left bottom",
            at: "left top",
        },
        focus: function (event, ui) {
           event.preventDefault();
        }

    });
});

Demo: http://jsfiddle.net/IrvinDominin/TgmPQ/

OTHER TIPS

focus: function (event, ui) {
       event.preventDefault();
 }

Try this. This will not change your value on focus! Please note your-input-field-id is the id of your input field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top