2014-03-14 77 views
1

我正在尝试为城市查找实现typeahead,但该字段没有更新。城市细节显示出来,但我需要在城市点击时在城市中显示该名称,但是当表单发送时,我只需要发送城市代码。typeahead not updating field

这是我的HTML:

<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " /> 

这是JavaScript:

$('#_hotelCity').typeahead({ 
    source: function (query, process) { 
     airports = [];  
     map = {}; 
     var data = (function() { 
      var data = null; 
      $.ajax({ 
       'async': false, 
       'global': false, 
       'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json', 
       'dataType': "json", 
       'success': function (jdata) { 
        data = jdata; 
       } 
      }); 
      return data; 
     })(); 

     $.each(data, function (i, airport) { 
      map[airport.complete_location] = airport; 
      airports.push(airport.city + ' (<b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location); 
     }); 

     process(airports);  
    }, 
    updater: function (item) { 
     selectedairport = map[item].complete_location; 
     selectedairport = map[item].iata_code; 
     return item; 
    }, 
    matcher: function (item) { 
     if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) { 
      return true; 
     } 
    }, 
    sorter: function (items) { 
     return items.sort(); 
    }, 
    highlighter: function (item) { 
     var regex = new RegExp('(' + this.query + ')', 'gi'); 
     return item.replace(regex, "<strong>$1</strong>"); 
    }, 
}); 

谢谢你的任何建议

+1

你使用的是什么版本的typeahead.js? typeahead.js没有“updater”,“matcher”,“sorter”或“highlighter”选项。 –

回答

0

HTML input标签只能有一个值。该值存储在内部并显示在该字段内。

看来你正在使用某种AJAX表单提交。 所以,你的解决方案是在JS中有单独的变量来存储城市代码。

另一种解决方案是使用Select2而不是键入。 当您提供类似于SELECT的字段但需要外部AJAX数据源时,这是我的选择。 顺便说一句,与选择2,你也可以强制用户只选择一个现有的价值。

看吧例如:http://ivaynberg.github.io/select2/#ajax

0

我会建议你使用你更新抛开正常的输入字段附加hidden场。

<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " /> 
<input type="hidden" value="" name="city_code" /> 

在这个隐藏字段中,每当更新typeahead时都会插入城市代码。提交表单时,服务器端脚本可以解析它(在PHP中,它将为$_POST['city_code'])。

0

使用typeahead,并不想取代你的代码。我结束了与此琴:http://jsfiddle.net/Ydtq9/2/

你一定会想重构一些东西,但关键是要设置一些实例变量在源功能,您可以访问他们在更新功能,像这样

$("#_hotelCity").typeahead({ 
    "source": function(query, process) { 
    this.map = ... 
    }, 
    "updater": function(item) { 
    var city = this.map(item) 

    //Then you can do what you need to with the original data. 
    } 
})