David Alzate David Alzate - 28 days ago 8
jQuery Question

change attrib name with array

I have a form with this input:

<input id="cant_user" type="text" name="cant_user" value="1" onblur="addInputs()">


#userData
is cloned when add a input value greater than 1 and I want to change input name from
user_age
to
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 + "]"
});
}
};
}
};
}


How can I make every label and input name shows a value from array like:

<label>Age User 1<label>
<input name="age[0]">
<label>Age User 2<label>
<input name="age[1]">

huy huy
Answer Source

I changed some code, it maybe can help if i understand your idea correct

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",);
    userAge.removeAttr("name","age[" + n + "]").attr("id","generatedAge[" + n + "]");
}