EasyAutocomplete - example

JQuery autocomplete plugin.

In the example below you can see how to use EasyAutocomplete plugin to interact with other elements on website.

When user selects one element from suggestion list, that elements value is inserted into another input. In this case when user selects one of the x-men characters, his/hers real name will appear in second text field.




Javascript:

var options = {

    url: "resources/xmen.json",

    getValue: function(element) {
        return element.character;
    },

    list: {
        onSelectItemEvent: function() {
            var selectedItemValue = $("#inputOne").getSelectedItemData().realName;

            $("#inputTwo").val(selectedItemValue).trigger("change");
        },
        onHideListEvent: function() {
        	$("#inputTwo").val("").trigger("change");
    	}
    }
};

$("#inputOne").easyAutocomplete(options);

HTML:

<input id="inputOne" placeholder="X-men character" />
<input id="inputTwo" placeholder="Real name" />

X-men.json

[
    {"character": "Cyclops", "realName": "Scott Summers"},
    {"character": "Professor X", "realName": "Charles Francis Xavier"},
    {"character": "Mystique", "realName": "Raven Darkholme"},
    {"character": "Magneto", "realName": "Max Eisenhardt"},
    {"character": "Storm", "realName": "Ororo Monroe"},
    {"character": "Wolverine", "realName": "James Howlett"}
]


This example uses function .getSelectedItemData(), that simply returns selected item data. When users selects first item from list, function .getSelectedItemData() returns object {"character": "Cyclops", "realName": "Scott Summers"}.

So in this example when user selects one of the characters from autocomplete list, function .getSelectedItemData() returns the data item and lets aquire other data fields, in this case realName.

Function onSelectItemEvent is invoked when item from autocomplete list is selected(read more in guide - event). This function first gets selected item data and inserts this value in another text field "#inputTwo".

Field "#inputTwo" is cleared, when list disappears, so when event onHideListEvent is fired.