Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery autocomplete : Preventing text replace when focus

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?

like image 857
Aneesh Avatar asked Dec 25 '22 22:12

Aneesh


1 Answers

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/

like image 100
Irvin Dominin Avatar answered Jan 18 '23 19:01

Irvin Dominin