使用Javascript创建动态输入ID [英] Use Javascript to create dynamic input id
问题描述
我想使用JavaScript创建具有动态id
(name
属性相同)的<input/>
标签,具体取决于它们出现的顺序.
I want to use javascript to create <input/>
tags with a dynamic id
(name
attribute will be the same) depending on the order in which they appear.
我在纯html中有第一个<input/>
标记,并且有一个div,该div应该在单击时附加一个新的<input/>
,且ID递增:
I have the first <input/>
tag in plain html and a div that should append a new <input/>
with an incremented id when clicked:
<input type="text" name="1" id="1" />
<div class="add_new" onClick="add_new_input()">+</div>
现在,javascript需要计算当前显示的<input/>
的数量(计数),并使用该数量生成动态的id
(计数+1).
Now, the javascript needs to count the amount of <input/>
s currently being displayed (count) and use that amount to generate a dynamic id
(count+1).
因此,如果两次单击<div class="add_new"><..
,则输出应如下所示:
Therefore if the <div class="add_new"><..
is clicked twice, the output should be as follows:
<input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<input type="text" name="3" id="3" />
如果我使用jquery的append()
在表单中添加新的<input/>
标记,这是否会添加到先前添加的<input/>
中?还是我需要附加一个<input/>
,然后两个,然后三个,依此类推?
If I append the new <input/>
tag in my form using jquery's append()
, would this add to the previously appended <input/>
s? Or would I need to append one <input/>
, then two, then three, etc?
此外,如何使用javascript计数当前显示的<input/>
的数量?
Also, how can I use javascript to count the amount of <input/>
s currently being displayed?
推荐答案
我使用了适合您要求的脚本.
I had used script which is fit in your requirement .
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>
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;
});
});
这篇关于使用Javascript创建动态输入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!