Jim*_*Jim 2 javascript jquery html-input bootstrap-typeahead typeahead.js
我正在使用typeahead.js从themoviedb api获取电影信息.当用户输入电影的标题时,我需要获得电影的年份和要自动添加到其他输入的电影的ID.
因此,当用户使用输入电影标题并点击建议的标题时,它会自动将年份和电影ID添加到其他输入
<input class="typeahead" placeholder="Movie Title Here"><br>
<input class="year" placeholder="Year Here">
<input class="id" placeholder="Year ID">
Run Code Online (Sandbox Code Playgroud)
看看接近返回(在第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>')
}
});
Run Code Online (Sandbox Code Playgroud)
这是我在jsfiddle上的代码,试试自己:
我在这里添加了一种自动填充相关输入控件的方法:
http://jsfiddle.net/Fresh/cmq80qx3/
实现自动填充的代码的关键部分是:
bind("typeahead:selected", function (obj, datum, name) {
$('.year').val(datum.year);
$('.id').val(datum.id);
});
Run Code Online (Sandbox Code Playgroud)
此代码指定在选择预先输入值时应调用的函数,在这种情况下,它会适当地设置year和id输入的值.