当select
发生变化时,您调用一个函数告诉Bloodhound使用哪个数组(或json文件/ url),然后让它重新运行它的initialize
函数来更新提示的建议列表。
HTML:
<h1>Typeahead Test </h1>
<select onchange="changeList(this.value)">
<option selected value="countries">Countries</option>
<option value="cities">Cities</option>
</select>
<input id="tags" name="tags" data-role="tagsinput" class="form-control input-sm tagsInput typeahead" type="text" placeholder="Enter some tags" title="Please enter some tags" value="" required>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<script src="bootstrap-tagsinput.min.js"></script>
的Javascript:
var country_list = ["Afghanistan", "Albania", "Algeria", "Andorra", "Auckland", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil"];
var city_list = ["Amsterdam", "London", "Paris", "Washington", "New York", "Los Angeles", "Sydney", "Melbourne", "Canberra", "Beijing", "New Delhi", "Kathmandu", "Cairo", "Cape Town", "Kinshasa"];
var myData = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(country_list, function(item) {
return {
value: item
};
})
});
myData.initialize();
$('#tags').tagsinput({
typeaheadjs: {
name: 'value',
displayKey: 'value',
valueKey: 'value',
source: myData.ttAdapter()
}
});
// utilised some code from http://stackoverflow.com/a/23000444/1544886
changeList = function(val) {
source = (val === 'cities') ? city_list : country_list;
myData.clear(); // First remove all suggestions from the search index
myData.local = $.map(source, function(item) {
return {
value: item
};
});
myData.initialize(true); // Finally reinitialise the bloodhound suggestion engine
};
这里有一个plunker:http://plnkr.co/edit/6mjDrgDwqzWeLJQOcA3D?p=preview
提供HTML代码,请 – webmaster
@webmaster完成。 – Peter
看看打字源。它可以是一个功能。在那里您可以读取其他inpuits值并构建所需的标签列表。 http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ – Andreyy