Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a array of objects as source for jQuery UI AutoComplete

If I have a array of objects like

var arrLinks = [
    { key: 1, url: "http://google.com" },
    { key: 2, url: "http://yahoo.com", title: "Yahoo" },
    { key: 2, url: "http://microsoft.com" }
];

Can I use it as the source for autocomplete? I tried implementing in following http://jqueryui.com/demos/autocomplete/#custom-data but didn't get it http://jsfiddle.net/mvNNj/

like image 228
Jiew Meng Avatar asked Jan 12 '11 11:01

Jiew Meng


1 Answers

You need to:

1 - Actually include jQuery + UI on your test page.

2 - Incorporate the use of 'labels' which the Autocompleter uses to find matches:

$(function() {
    var arrLinks = [
        {
        key: 1,
        url: "http://google.com",
        label: 'google'},
    {
        key: 2,
        url: "http://yahoo.com",
        title: "Yahoo",
        label: 'yahoo'},
    {
        key: 2,
        url: "http://microsoft.com",
        label: 'microsoft'}
    ];
    $("input[name=url]").autocomplete({
        source: arrLinks
    }).data("autocomplete")._renderItem = function(ul, item) {
        return $("<li>").data("item.autocomplete", item).append("<a>" + item.url + "</a>").appendTo(ul);
    };
});

Your test page, working.

like image 116
karim79 Avatar answered Oct 14 '22 03:10

karim79