2016-11-15 8 views
0

我有一個HTML表單從數據庫中讀出數據。該表單包含一個來自awesomeplete的自動完成功能,該功能顯示數據庫中的值,可以在輸入字段中輸入至少兩個字母后選擇該值。這工作正常!從awesomeplete的自動完成功能不能在另外創建的輸入字段中通過javascript

現在,我已經加入到創建使用下面的JavaScript函數的其他輸入字段的可能性:

enter code here 

    <script> 
    var counter = 1; 

    var limit = 10; 

    function addInput(divName){ 

     if (counter == limit) { 

       alert("You have reached the limit of adding " + counter + " 
    inputs"); 

     } 

     else { 

       var newdiv = document.createElement('div'); 

       newdiv.innerHTML = '<br><input type="text" 
    id="productinput11" name="productinput[]" class="awesomplete" 
    list="productinputselect" size="20"/>'; 

       document.getElementById(divName).appendChild(newdiv); 

       counter++; 

     } 

    } 
    </script> 

     <div id="dynamicInput"> 
     <b></b><input type="text" id="productinput11" name="productinput 
    []" class="awesomplete" list="productinputselect" size="20"/> 
     </div> 
     <input type="button" value="Weiteres Eingabefeld" onClick="addInput 
    ('dynamicInput');"> 

enter code here 

現在的問題是,從awesomeplete自動完成功能只能在這第一個輸入字段函數,並且在附加創建的輸入字段中不再存在,儘管class =「awesomplete」存在於任何地方。 如何使此功能可以在所有添加的輸入字段中工作?

回答

0

您的Awesomplete已爲所有.awesomplete類元素加載。

如果添加一些,則必須重新實例化Awesomplete

所以,你的其他statment應該是這樣的

function addInput(divName){ 
    if (counter == limit) { 
    [...] 
    } else { 
    // Create new div 
    var newdiv = document.createElement('div'); 
    newdiv.innerHTML = '<br><input type="text" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>'; 
    document.getElementById(divName).appendChild(newdiv); 

    // Re instantiate Awesomplete 
    new Awesomplete(newdiv.querySelector('input'), { list: document.querySelector('#productinputselect') }); 

    // Set counter 
    counter++; 
    } 
} 

這裏工作爲例

var newdiv = document.createElement('div'); 
 
newdiv.innerHTML = '<br><input type="text" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>'; 
 
document.body.appendChild(newdiv); 
 

 
new Awesomplete(
 
\t newdiv.querySelector('input'), 
 
    { list: document.querySelector('#productinputselect') } 
 
);
<script src="https://leaverou.github.io/awesomplete/awesomplete.js"></script> 
 
<datalist id="productinputselect"> 
 
\t <option>Ada</option> 
 
\t <option>Java</option> 
 
\t <option>JavaScript</option> 
 
\t <option>Brainfuck</option> 
 
\t <option>LOLCODE</option> 
 
\t <option>Node.js</option> 
 
\t <option>Ruby on Rails</option> 
 
</datalist>

順便說,我去掉你id=""屬性的新的輸入元素,因爲ID attribu te 必須是唯一的

答案基礎上,Awesomplete API documentation

+0

謝謝Robiseb!我試過你的解決方案,但結果與以前一樣。 – Columbus

+0

好吧,我已經知道了。我在第一個'Awesomplete()'參數上使用了一個jQuery DOM元素,而不是_pure_元素。 – Robiseb

+0

非常感謝Robiseb! 'document.getElementById(divName).appendChild(newdiv);'你的第一個答案,而不是'document.body.appendChild(newdiv);'它工作完美! :) – Columbus