【发布时间】:2014-12-07 12:14:57
【问题描述】:
我正在使用 typeahead.js 从 themoviedb api 获取电影信息。当用户输入电影的标题时,我需要获取电影的年份和电影的 ID,以便自动添加到其他输入中。
所以当用户使用输入的电影标题并点击建议的标题时,它会自动将年份和电影 ID 添加到其他输入中
HTML 代码
<input class="typeahead" placeholder="Movie Title Here"><br>
<input class="year" placeholder="Year Here">
<input class="id" placeholder="Year ID">
JS代码
靠近返回(在第 12 行)有我需要转移到其他输入的信息
var movies = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: {
url: 'http://api.themoviedb.org/3/search/movie?api_key=470fd2ec8853e25d2f8d86f685d2270e&query=%QUERY&search_type=ngram',
filter: function (movies) {
// Map the remote source JSON array to a JavaScript array
return $.map(movies.results, function (movie) {
return {
id: movie.id,
value: movie.original_title,
year: (movie.release_date.substr(0,4) ? movie.release_date.substr(0,4) : '')
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead({
hint: true,
highlight: true
}, {
displayKey: 'value',
source: movies.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
}
});
这是我在 jsfiddle 上运行的代码,供您尝试:
【问题讨论】:
标签: javascript jquery typeahead.js bootstrap-typeahead html-input