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

时间:2017-08-29 08:12:49

标签: javascript jquery html ajax autocomplete

我正在使用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无效。有什么问题?

1 个答案:

答案 0 :(得分:1)

从我理解的评论中你想要的只是将输入的初始值附加到建议对象上,以便它作为前缀。

你为什么不这么说?

使用您的代码:

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