javascript - 预输入不更新字段

标签 javascript bootstrap-typeahead typeahead.js

我正在尝试实现城市查找的提前输入,但该字段没有更新。显示了城市详细信息,但我需要在单击城市时显示城市名称,但发送表单时,我只需要发送城市代码。

这是我的 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,您还可以强制用户仅选择现有值。

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

关于javascript - 预输入不更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22395629/

相关文章:

javascript - 如何使 JSON 数组唯一

javascript - Sequelize 多对多添加功能不起作用

javascript - 使用 Twitter 的 typeahead.js - 调用我的 WebAPI,如何在我的 typeahead 输入文本框中填写下拉列表?

javascript - 更新内容时出错

javascript - 如何使用 NodeJS 运行文件夹中的所有 javascript 文件?

javascript - Typeahead Wait 发出多个请求,而不仅仅是最后一个

javascript - 在 AngularJS 中,我可以/应该从 Controller 增强模型吗?

javascript - 不显示时滚动到div的顶部

javascript - Vuejs + typeahead this - 未定义

javascript - typeahead js不显示结果