自动完成动态创建的输入

时间:2014-06-13 18:06:19

标签: jquery html

我试图将其他方面的答案纳入本主题,但它们似乎并不适合我。我有可能做错了......我想做的就是它在标题中所说的内容。到目前为止,我已经创建了JSFiddle。任何帮助将不胜感激。

JSFiddle

HTML

<div id="newlink">
    <div>
        <input id="stores[]" class="stores" placeholder="Start typing code or name of item">
        <input name="itemcount[]" type="tel" placeholder="Quantity" value="" maxlength="5" />
        <br />
    </div>
</div>
 <h2 id="addnew">
<a class="add" href="javascript:new_link()">Add Line</a>

<div id="newlinktpl" style="display: none">
    <div>
        <input id="stores[]" class="stores" placeholder="Start typing code or name of item">
        <input name="itemcount[]" type="tel" placeholder="Quantity" value="" maxlength="5"/>
     <br />
    </div>
</div>

JS

$(function () {
    var choices = [
        "Pizza",
        "Fries",
        "Milkshake"];

    $('.stores').autocomplete({
        source: choices,
        messages: {
            noResults: '',
            results: function () {}
        }
    });
});


var ct = 1;
function new_link() {
    ct++;
    var div1 = document.createElement('div');
    div1.id = ct;

    div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
    document.getElementById('newlink').appendChild(div1);
}

1 个答案:

答案 0 :(得分:2)

<强> Live demo

每次创建新输入字段时都需要指定事件。那么你如何做到这一点:

var choices;
$(function () {
    choices = [
        "Pizza",
        "Fries",
        "Milkshake"];

    autocomplete();
});

function autocomplete(){
 $('.stores').autocomplete({
        source: choices,
        messages: {
            noResults: '',
            results: function () {}
        }
    });
}

var ct = 1;
function new_link() {
    ct++;
    var div1 = document.createElement('div');
    div1.id = ct;

    div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
    document.getElementById('newlink').appendChild(div1);
    autocomplete();

}