我正在尝试实现城市查找的提前输入,但该字段没有更新。显示了城市详细信息,但我需要在单击城市时显示城市名称,但发送表单时,我只需要发送城市代码。
这是我的 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>" );
},
});
感谢您的建议
最佳答案
HTML input
标签只能有一个值。该值存储在内部并显示在字段内。
您似乎正在使用某种 AJAX 表单提交。 因此,您的解决方案是在 JS 中使用单独的变量来存储城市代码。
另一个解决方案是使用 Select2 而不是 typeahead。 当您提供类似 SELECT 的字段但需要外部 AJAX 数据源时,这是我的选择。 顺便说一句,使用 Select2,您还可以强制用户仅选择现有值。
关于javascript - 预输入不更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22395629/