2017-08-29 29 views
0

我與Ajax autocomplete for jquery的工作和我的HTML代碼阿賈克斯自動完成的jQuery不工作當文本字段不爲空

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

,它是工作罰款,但當我在文本字段中添加值屬性:

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

添加值autocomplete不起作用。問題是什麼?

+0

則需要使用JavaScript – masterpreenz

+0

在控制檯中的任何錯誤設定值? – Se0ng11

+0

值已經設置並來自數據庫。 – user3833682

回答

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/


替代WOU LD是ES6箭頭功能與.MAP()函數:

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

它只顯示'國家'變量的標籤不是整個文本框的值,'約翰'的值可以變成某些東西,因爲'約翰'值來自數據庫,自動建議將顯示來自'國家'變量的 而不是整個價值。 – user3833682