我知道这个问题被问了很多次,但同样不适合我。我想强制用户在typeahead中选择结果,如果他没有选择模糊空输入框。
我在模糊,typeahead:selected上使用了类型。在模糊工作,但我没有得到选定的数据和typeahead:选择不起作用
请参阅此链接以获取早期回答link1,link2和link3
以下是我的onblur代码
var newData = [];
$('.search').each(function() {
var idName = this.id;
var $this = $(this);
$this.typeahead({
source:function(query,process){
if( typeof searching != "undefined") {
clearTimeout(searching);
process([]);
}
searching = setTimeout(function() {
return $.getJSON(
"batchEnable.jsp?autosearch="+idName,
{ q:query },
function(data){
$.each(data, function(){
newData.push(this.name);
});
// only search if stop typing for 300ms aka fast typers
return process(newData);
});
}, 300); // 300 ms
},
}).blur(function(){
if(newData[$(this).val()] == null) {
// I am always getting this null (newData[$(this).val()]),
//if even if I select typeahead result data
$('#'+idName+'').val('');
newData = [];
}
});
});
on select with with的代码在选择预先输入数据时未被调用
.on('typeahead:selected', function (obj, datum) {
console.log(datum); // datum will contain the value that was autocompleted
});
答案 0 :(得分:1)
我在字段0和1的字段中保留了隐藏值。如果他从typeahead中选择结果然后调用updater函数并且我将标志值设置为1并且如果flag不等于1则onblur然后我将清空输入文本框onblur。还有一件事,每当用户输入任何东西时我都会清除标志值。
以下是为此工作的代码。
$('.search').each(function() {
var idName = this.id;
var $this = $(this);
var map = {};
$this.typeahead({
source:function(query,process){
if( typeof searching != "undefined") {
clearTimeout(searching);
process([]);
}
searching = setTimeout(function() {
return $.getJSON(
"batchEnable.jsp?autosearch="+idName,
{ q:query },
function(data){
var regions = [];
$("#"+idName+"_").val("");
$.each(data, function(){
map[this.name] = this.id;
regions.push(this.name);
});
// only search if stop typing for 300ms aka fast typers
process(regions);
});
}, 300); // 300 ms
},
updater: function (item) {
selectedState = map[item];
// this will set id in input hidden as per the idname_
$("#"+idName+"_").val(selectedState);
return item;
}
}).blur(function(){
// onblur check if user has selected value in typeahead drop down if he has not selected then hidden value will be blank and then empty input text also
var hiddenValue = $("#"+idName+"_").val();
if(hiddenValue == null || hiddenValue == ""){
$("#"+idName).val("");
}
});
});