0

我知道这个问题被问了很多次,但同样不适用于我。如果他没有在模糊空输入框中选择,我想强制用户在输入前选择结果。

我使用了类似模糊的类型,typeahead:selected。模糊正在工作,但我没有得到选定的数据并且预先输入:selected 根本不工作

请参阅此链接以获取较早的答案link1link2link3

下面是我的 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 selected with 的代码

.on('typeahead:selected', function (obj, datum) {
    console.log(datum);  // datum will contain the value that was autocompleted
 });
4

1 回答 1

1

我在带有标志 0 和 1 的字段中保留了隐藏值。如果他从预先输入的结果中选择结果,则将调用更新器函数,并且我将标志值设置为 1,如果标志不等于 1,则设置为 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("");      
  }
 });
});
于 2014-08-13T10:32:43.697 回答