我想通过点击添加按钮,使用下面的javascript动态地将表单输入字段添加到表单中:
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("Name", "a_level[ + i ][0]");
r.appendChild(y);
z.setAttribute("Name", "a_level[ + i ][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class = "dash-form" method = "POST" action = "/" >
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[+i][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[+i][1]" value = "" placeholder = "Course"/>
</div>
<div class = "dash-submit">
<input class = "dash-submit-button" type = "submit" value = "Submit"/>
</div>
</form>
<div class = "dash-add">
<button class = "dash-add-button" onclick = "addfieldFunction()">ADD</button>
</div>
该函数返回 i ,而不是递增并返回一个整数,如下所示:
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[0][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[0][1]" value = "" placeholder = "Course"/>
</div>
答案 0 :(得分:4)
使用i
运算符
+(concatenation operator)
concatenation operator
(+)
将两个字符串值连接在一起,返回另一个字符串,即两个操作数字符串的union
。
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("name", "a_level[ " + i + " ][0]"); //Keep attribute in lower case
r.appendChild(y);
z.setAttribute("name", "a_level[ " + i + "][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
&#13;
<form class="dash-form" method="POST" action="/">
<div id="form-div">
<input class="dash-input" type="text" name="a_level[+i][0]" value="" placeholder="University" />
<input class="dash-input" type="text" name="a_level[+i][1]" value="" placeholder="Course" />
</div>
<div class="dash-submit">
<input class="dash-submit-button" type="submit" value="Submit" />
</div>
</form>
<div class="dash-add">
<button class="dash-add-button" onclick="addfieldFunction()">ADD</button>
</div>
&#13;
答案 1 :(得分:3)
你需要像这样连接它:
y.setAttribute("name", "a_level[" + i +"][0]");
正如Rayon指出的那样:尽管HTML5标准不需要小写属性名称,但保持属性为小写(参见here)。 W3C推荐它,但XHTML验证将使用大写字母失败。