javascript - 当文本字段不为空时,Ajax 自动完成 jquery 不起作用

标签 javascript jquery html ajax autocomplete

我正在使用 jquery 的 Ajax 自动完成功能,我的 HTML 代码是

<input type="text" name="autocomplete" id="globalBCCAutoComplete">

我的自动完成 JS代码是

$(document).ready(function() {
    var countries = [
        { value: '{contract_name}', data: 'Contact Name'},
        { value: '{user_company}', data: 'User Company' }
    ];
    $('#globalBCCAutoComplete').autocomplete({
        lookup: countries,
        onSelect: function (suggestion) {
            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
            console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
        }
    });
});

它工作正常,但是当我在文本字段中添加 value 属性时:

<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="This is test">

添加值后自动完成不起作用。有什么问题吗?

最佳答案

从评论中我了解到您想要的只是将输入上设置的初始值附加到建议对象,以便它将充当前缀。

你为什么不这么说?

使用您的代码:

HTML:

<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="john">

JavaScript:

$(document).ready(function() {

        let countries = [
           { value: '{contract_name}', data: 'Contact Name'},
           { value: '{user_company}', data: 'User Company' }
        ];

        //get current value from the textbox
        let initialTextValue = $('#globalBCCAutoComplete').val().trim();

        //append the value to your JSON objects.
        $(countries).each(function(key, country) {
            country.value = initialTextValue + ' ' + country.value
        });

        //the rest of your code:
        $('#globalBCCAutoComplete').autocomplete({
            lookup: countries,
            onSelect: function (suggestion) {
                console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
            }
        });
    });

jsfiddle 示例:https://jsfiddle.net/7g4nnnoz/5/

<小时/>

另一种选择是带有 .map() 函数的 ES6 箭头函数:

//append the values to the json object.
countries.map( (country) => {
    country.value = initialTextValue + ' ' + country.value
});

关于javascript - 当文本字段不为空时,Ajax 自动完成 jquery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45933955/

相关文章:

html - 一页上的多个 Z-index 元素

javascript - 我可以将 jquery 处理程序放入构造函数中吗?

javascript - 如果我打算使用 Node,那么直接使用像 Zappa 这样的 CoffeeScript 框架是错误的吗?

javascript - 无法使用 react 中的状态增加计数

javascript - 在 Javascript 中将 XMLHttpRequest 转换为字符串

javascript - 在 owl carousel mobile 上显示 3 个元素

javascript - 使用 Javascript 更改 head 标签内 CSS 的顺序

javascript - 每次用户刷新页面时不同的JS动画

html - CSS 问题 : why my css stylesheet selector not working?

javascript - 如何有条件地填充数组?