I wrote a function to add listitem with a text box and a remove button, everytime the add button was clicked. i'm also adding a unique id to each new element by adding a number. the problem happens when i try to remove an element, then add another one, sometimes that number is being duplicated. ex: I add 4 li's and decide to remove #3. Then click add new again the new sequence is 1,2,4,3,4 instead of 1,2,4,5,6. I hope that made sense.
here is my javascript
var count = 2;
$('#add').click(function() {
var newTxtBxLi = $('<li></li>').attr('id', 'newli' + count).appendTo('ul');
var input = $('<input type="text" id="newinput' + count + '" name="newinput' + count + '" /><input type="button" id="remove' + count + '" class="remove" value="">');
$(input).appendTo(newTxtBxLi);
count++;
$('.remove').each(function() {
$(this).click(function() {
//count--;
$(this).parent('li').remove();
});
});
});
Thanks, in advance
//update so i was doing some research on stackoverflow, and found a post about performing a check for duplicate id's. the new code works, but now i have to figure out how to write "find the last id and + 1, then create new li with this new id. here is my updated code:
$('#add').click(function() {
var count = $('ul > li').length + 1;
var newTxtBxLi = $('<li></li>').attr('id', 'newli' + count).appendTo('ul');
var input = $('<input type="text" id="newinput' + count + '" name="newinput' + count + '" /><input type="button" id="remove' + count + '" class="remove" value="">');
$('ul > li[id]').each(function(){
var ids = $('[id='+this.id+']');
if(ids.length>1 && ids[0]==this){
//console.warn('Multiple IDs #'+this.id);
//find the last id and + 1, then add new listitem
}else{
$(inputAcc).appendTo(newTxtBxLi);
accomplishCount++;
}
});
$('.remove').each(function() {
$(this).click(function() {
count--;
$(this).parent('li').remove();
});
});
});