我试图用一组静态数据选项做一个简单的选择框。
<input type="text" id="qs-city-select" name="city" class="typeahead tt-input" autocomplete="off" placeholder="Type a city">
我的jquery代码如下:
<script type="text/javascript">
jQuery(document).ready(function($){
var numbers = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: [
{ "value": "21", "name": "Twenty one" },
{ "value": "22", "name": "Twenty two" },
]
});
numbers.initialize();
$('#qs-city-select').typeahead({hint: false}, {
displayKey: 'value',
source: numbers.ttAdapter()
});
});
我希望可见选项选择为&#34;二十一&#34;和&#34;二十二&#34;然后通过表格传递21或22的值。我无法让这个工作。我只能让它在显示的地方工作,并作为一个值传递相同的字符串。
我做错了什么?
答案 0 :(得分:1)
因为在html输入节点上有预先模仿,我相信它总会将该输入的值设置为向用户显示的值。您可以更改typeahead js并可能更改此功能的脚本,或者我要做的是绑定到&#34; select&#34; typeahead的事件并设置另一个隐藏的html输入的值。
这是:
jQuery(document).ready(function($){
var numbers = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name + " " + d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: [
{ "value": "21", "name": "Twenty one" },
{ "value": "22", "name": "Twenty two" },
]
});
numbers.initialize();
var a = $('#qs-city-select').typeahead({hint: false}, {
displayKey: 'name', //displays the name value of the datum to the end user eg. "Twenty one"
source: numbers.ttAdapter()
});
$('#qs-city-select').bind('typeahead:select', function(e, datum) {
$('#qs-city-select').typeahead('val', datum.name); //Use the typeahead api to override default behaviour of setting the typeaheads value to the datums value ie from "21" to "Twenty one"
$('#hidden-input').val(datum.value); //set the hidden inputs value to the datum value eg. "21"
console.log($('#hidden-input').val());
});
});
这是一个有效的js Fiddle:
备注:根据您希望用户字符串匹配的内容,您可以更改
return Bloodhound.tokenizers.whitespace(d.name) //match on "Twenty one" etc
到
return Bloodhound.tokenizers.whitespace(d.value) //match on 21, 22 etc
或两者匹配
return Bloodhound.tokenizers.whitespace(d.name + " " + d.value) //match on"Twenty one" or "21"