Javascript 输入未更新字段
我正在尝试为城市查找实现typeahead,但该字段没有得到更新。城市详细信息会显示出来,但我需要在单击城市时在城市中显示名称,但在发送表单时,我只需要发送城市代码 这是我的HTML:Javascript 输入未更新字段,javascript,bootstrap-typeahead,typeahead.js,Javascript,Bootstrap Typeahead,Typeahead.js,我正在尝试为城市查找实现typeahead,但该字段没有得到更新。城市详细信息会显示出来,但我需要在单击城市时在城市中显示名称,但在发送表单时,我只需要发送城市代码 这是我的HTML: <input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " /> 这是javascript: $('#_hotelCity').typ
<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输入标记只能有一个值。该值存储在内部,并显示在字段内
看起来您正在使用某种AJAX表单提交。
所以,您的解决方案是在JS中使用单独的变量来存储城市代码
另一个解决方案是使用Select2而不是typeahead。
当您提供类似SELECT的字段但需要外部AJAX数据源时,这是我的选择。
顺便说一句,使用Select2还可以强制用户仅选择现有值
例如,请看这里:我建议您使用一个额外的隐藏字段,将其更新到普通输入字段之外
<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解析表单,它将使用typeahead$\u POST['city\u code'..,并且不想替换太多的代码。我最终得到了这把小提琴: 你肯定会想要重构一些东西,但诀窍是在源函数中设置一些实例变量,你可以像这样在updater函数中访问它们
$("#_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.
}
})
您使用的是什么版本的typeahead.js?typeahead.js没有更新程序、匹配程序、分类器或荧光笔选项。