Reputation:
I have a function that adds div when I press a button. I have a counter re-setting logic written in the removal which should re-count all my names.
my problem is that when I add say 3 items, and remove the 2nd Item, my 3rd item does not rename itself.
what am I doing wrong with this?
$(function () {
var rowItem = $(".row", $(".formitems")); //select all rows from class formitems
$(".formitems").on("click", ".addRow", function () {
var newItem = rowItem.clone(),
rowIndex = $(".row", $(".formitems")).length;
$(":input", newItem).each(function (c, obj) {
$(obj).attr("name", $(obj).attr("crap") + rowIndex);
});
$(".formitems").append(newItem); // adds At the end of the container
}).on("click", ".removeRow", function () {
if ($(".row", $(".formitems")).length > 1) {
var target = $(this).parent().parent().parent().parent(".row");
target.slideUp(function () {
target.remove();
});
}
for (i = 0; i < $(".row", $(".formitems")).length; i++) //select our div called //formitems and then count rows in it
{
rowobj = $(".row", $(".formitems"))[i];
$(":input", rowobj).each(function (c, obj) {
$(obj).attr("name", $(obj).attr("crap") + i);
})
}
});
});
EDIT : Ok, So I put up alerts just before and after using remove(). Does jquery takes time to re-calulate all the properties? If yes, are they cached? If yes, can I force refresh them.?
Upvotes: 0
Views: 69
Reputation: 885
As far as i understand, you want to update the 'name's after the removal. But the code does the remove() asynchronously when slideUp() completed, while the renaming is invoked immediately after invoking the slideUp(), before remove() is called.
You can solve this by placing the renaming code after the call to remove(), inside the slideUp() handler:
}).on("click", ".removeRow", function () {
if ($(".row", $(".formitems")).length > 1) {
var target = $(this).parent().parent().parent().parent(".row");
target.slideUp(function () {
target.remove();
// rename now!
for (i = 0; i < $(".row", $(".formitems")).length; i++) {
rowobj = $(".row", $(".formitems"))[i];
$(":input", rowobj).each(function (c, obj) {
$(obj).attr("name", $(obj).attr("crap") + i);
})
}
});
}
});
Upvotes: 0
Reputation: 324650
Consider simplifying your life.
<input type="text" name="blah[]" />
You can have as many of these elements as you want. The server will receive an array of values, meaning you don't have to manually count them.
Upvotes: 1