2015-11-13 93 views
3

我不確定要正確標題,但我需要做的事情在理論上相當簡單。過去我使用Twitter的typeahead.js來查找預定義列表中的值。然而,現在我需要返回其他根據他們鍵入的內容,輸入的內容。typeahead方法返回相關結果

我有一個名稱和ID列表 - 用戶將知道名稱,但不知道ID。當他們輸入名稱時,下拉列表需要下拉與該名稱關聯的任何ID。

typeahead.js框架會爲此工作嗎?如果是這樣,我該怎麼做?我找不到任何在線文檔(或者我不知道該怎麼尋找?)

我的JSON看起來就像這樣:

{ 
    "1": { 
     "name": "John", 
     "ID": "1234" 
    }, 
    "2": { 
     "name": "Bob", 
     "ID": "2345" 
    }, 
    "3": { 
     "name": "Matt", 
     "ID": "3456" 
    }, 
    "4": { 
     "name": "John", 
     "ID": "9874" 
    } 
} 

所以如果在「約翰用戶類型「我要的下拉菜單返回兩個值:

1234 
9874 

我不反對使用除了typeahead.js其他的東西,如果它不具有此功能。

回答

2

typeahead.js仍然是您嘗試完成的最佳選擇。

這裏是一個工作示例小提琴:

https://jsfiddle.net/5fspsx79/

var substringMatcher = function(strs) { 
return function findMatches(q, cb) { 
    var matches, substringRegex; 
    matches = []; 
    substrRegex = new RegExp(q, 'i'); 
    $.each(strs, function(i, str) { 
    if (substrRegex.test(str.name)) { 
     matches.push(str); 
    } 
    }); 
    cb(matches); 
}; 
}; 

var people = [{ 
    "name": "John", 
    "ID": "1234" 
},{ 
    "name": "Bob", 
    "ID": "2345" 
},{ 
    "name": "Matt", 
    "ID": "3456" 
},{ 
    "name": "John", 
    "ID": "9874" 
}]; 

$('#custom-templates .typeahead').typeahead(null, { 
    name: 'people', 
    display: 'ID', 
    source: substringMatcher(people), 
    templates: { 
    empty: [ 
     '<div class="empty-message">', 
     'unable to find any results.', 
     '</div>' 
    ].join('\n'), 
    suggestion: Handlebars.compile('<div>{{ID}}</div>') 
    } 
}); 

你只需要添加自定義模板。

有一個例子: http://twitter.github.io/typeahead.js/examples/

具體而言,看自定義模板

+0

非常感謝凱爾。如果我有任何疑問,我會仔細研究並告訴你! –