【问题标题】:Ajax autocomplete jquery is not working when text field is not empty当文本字段不为空时,Ajax 自动完成 jquery 不起作用
【发布时间】:2018-02-06 14:32:58
【问题描述】:

我正在使用Ajax autocomplete for jquery,我的 HTML 代码是

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

而我的autocomplete 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">

添加值后autocomplete 不起作用。有什么问题?

【问题讨论】:

  • 你需要使用javascript设置值
  • 控制台有错误吗?
  • 值已设置并来自数据库。
  • @Se0ng11 控制台没有错误..
  • 我也试过jquery UI它在我的情况下没有任何替代方案。

标签: javascript jquery html ajax autocomplete


【解决方案1】:

从 cmets 我知道你想要的只是将输入上设置的初始值附加到建议对象,以便它充当前缀。

你为什么不这么说?

使用您的代码:

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
});

【讨论】:

  • 它只显示countries 变量的标签而不是整个文本框的值,John 值可以更改为某些值,因为John 值来自数据库并且自动建议将显示来自countries 变量不是整个值。
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2015-04-27
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多