I have the following:
<!-- group clone //-->
<div class="section">
<div class="parent row infoOn">
<div class="validGroup">
<a title="remove" class="iconClose" href="#">remove</a>
<div class="grouping">
<div class="clearfix valid">
<label>Name<span class="iconReq"> </span>:</label>
<input type="password" class="text inpButton" name="items[0].first">
</div>
<div class="clearfix">
<label>Email<span class="iconReq"> </span>:</label>
<input type="text" class="text inpButton" name="items[0].first">
</div>
</div>
</div>
</div>
<div class="row addControl">
<a href="#" class="button">Add</a>
</div>
</div>
<!-- group clone //-->
and jQuery:
$(function(){
// Control clone
$('div.addControl a.button').click(function (e){
e.preventDefault();
var parent = $(this).closest('.section').find('.parent:last');
var parentInput = parent.clone();
parentInput.find("input").val("");
parent.after(parentInput);
});
$('div.validGroup a.iconClose').live('click', function (e){
e.preventDefault();
if ($(this).closest('.section').find('.parent').length > 1){
$(this).closest('div.parent').remove();
}
});
reflesh();
});
Question: how would I change it so that when adding OR removing a new group, input fields would be renamed to name="items[INDEX].first"
and name="items[INDEX].last"
For example. when there's only one "group", input fields would have names:
name="items[0].first"
name="items[0].last"
if I add another one, the new one would have
name="items[1].first"
name="items[1].first"
and so on.
When I remove the first one (one with items[0].first
), the second one's input names would be modified from "items[1].first"
to items[0].first
.
here is what it looks like:
I figured it out:
var size = parseInt($('.form .section .parent').size());
$('.form .section .parent').each(function(index){
$(this).find('input.text').each(function(){
$(this).attr("name", $(this).attr("name").replace($(this).attr("name").match(/\[[0-9]+\]/), "["+index+"]"));
});
if (size > 1) { $(this).find('a.iconClose').show(); }else{ $(this).find('a.iconClose').hide(); }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With