var x = 0;
var counter = 0 ;
$(function () {
$('#addBtn').click(function () {
x++;
if (counter < 5) {
counter++;
$('#content').append('<input type="text" id="mytxt' + x + '">');
$('#content').append('<input type="button" id="removeBtn' + x + '" value="Remove" onclick="removeRow(' + x + ')" />');
$('#content').append('<div id="br' + x + '"/></div>');
} else {
alert("you cannot added more than 5 element");
}
}
);
});
function removeRow(index) {
$('#mytxt' + index).remove();
$('#removeBtn' + index).remove();
$('#br' + index).remove();
counter--;
alert(counter);
}
this is my function to create dynamic button, when i clicked “addBtn”, new element will be created and id start with 1,eg: mytxt1, and when i clicked “removeBtn” and “addBtn” again,the id will become mytxt2, the result is out of my expected,
what i want is when i clicked “removeBtn” and “addBtn” ,the id will start from 1 again,but not 2
new updated
that is one of my question also, if i added more element let said 4 element,the id i get will be mytxt1,mytxt2,mytxt3 and mytxt4, and if i remove mytxt2, the next element i added will become mytxt1,mytxt3,mytxt4,and mytxt5, and this is not what i want,what i want is mytxt1,mytxt2,mytxt3 and mytxt4
The following (untested) code keeps track of which indexes have been used, and allows reuse of indexes formerly associated with removed items. Note that the user could remove items in any order; this code reuses lower indexes first.
EDIT: Note, I kept this as similar to your starting code as I could, but I removed the
countervariable entirely because my code doesn’t use it – obviously you can put it back (with correspondingcounter++andcounter--in the appropriate places) if you want instant access to the current count of elements.