使用Javascript创建动态输入ID

pro*_*het 3 html javascript jquery

我想使用javascript创建<input/>具有动态标签idname属性将相同),具体取决于标签显示的顺序。

<input/>在纯html中有第一个标签,并且有div,<input/>当单击时,该div应该附加一个带有递增ID 的新标签:

<input type="text" name="1" id="1" />
<div class="add_new" onClick="add_new_input()">+</div>
Run Code Online (Sandbox Code Playgroud)

现在,javascript需要计算<input/>当前显示的s 的数量(计数),并使用该数量来生成动态值id(count + 1)。

因此,如果<div class="add_new"><..单击两次,则输出应如下所示:

<input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<input type="text" name="3" id="3" />
Run Code Online (Sandbox Code Playgroud)

如果我<input/>使用jquery的形式在表单中添加新标签append(),这会添加到之前附加的<input/>s吗?还是我需要追加一个<input/>,然后两个,然后三个,依此类推?

另外,如何使用javascript计数<input/>当前显示的s 数量?

Roo*_*dra 6

我使用了适合您要求的脚本。

HTML:

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
    <p>
    <label for="p_scnts">
        <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
    </label>
    </p>
</div>
Run Code Online (Sandbox Code Playgroud)

Javascript:-

  $(function () {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;

    $('#addScnt').live('click', function () {
    $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
    i++;
    return false;
    });

    $('#remScnt').live('click', function () {
    if (i > 2) {
        $(this).parents('p').remove();
        i--;
    }
    return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

working demo