我有一个带有此输入的表单:
<input id="cant_user" type="text" name="cant_user" value="1" onblur="addInputs()">
添加大于1的输入值时会克隆 #userData
,我想将输入名称从user_age
更改为age[n]
<div id="userData">
<div class="panel-body" id="generated[0]">
<div class="form-group">
<label class="col-md-4 control-label">Age User [n]</label>
<div class="col-md-6">
<input type="number" class="form-control" name="user_age[]" value="0" required>
</div>
</div>
</div>
Javascript:
function addInputs() {
var cantUsers = document.getElementById("cant_user").value;
var countGenerated = $('[id^=generated]').length;
if (countGenerated > 0) {
$('[id^=generated]').not(':first').remove();
}
if (cantUsers != 1) {
if (cantUsers > 1 && cantUsers < 10) {
for (var i = 1; i < cantUsers; i++) {
jQuery("#userData").append(jQuery("#userData").children().first().clone());
jQuery("#userData").children().last().attr("id", "generated[" + i + "]");
for (var n = 0; n <= i; m++) {
var u = document.getElementsByName("user_age[]");
$(u).removeAttr("name").attr({
id: "generatedAge[" + n + "]",
name: "age[" + n + "]"
});
}
};
}
};
}
如何使每个标签和输入名称显示数组中的值,如:
<label>Age User 1<label>
<input name="age[0]">
<label>Age User 2<label>
<input name="age[1]">
答案 0 :(得分:0)
我更改了一些代码,如果我理解你的想法正确可能会有所帮助
for ( var i = 1; i < cantUsers; i++) {
var userData = jQuery("#userData");
var childOfUserData = userData.children();
userData.append( childOfUserData.first().clone() );
childOfUserData = userData.children(); //because we just appen new data
childOfUserData.last().attr("id","generated[" + i + "]");
for ( var n = 0; n <= i; n++ ) {
var child = childOfUserData.get(i);
var userAge = $("input", $(child));//because you only have one input
userAge.attr("name","age[" + n + "]").attr("id","generatedAge[" + n + "]");
}
答案 1 :(得分:0)
<input name="age[0]">
在上面的代码name
中,属性值充当文本而不是数组值。
要在attribute
中获取数组值,您需要更改JavaScript
代码
$("#userData").children().last().attr("id", generated[i]);
$(u).removeAttr("name").attr({
id: generatedAge[n],
name: age[n]
});
现在,如果您检查属性值,您将收到数据。
希望这会对你有所帮助。