Reputation: 16691
Im trying to remove a div that has been inserted by my previous Jquery code.
$counter = 0;
$("#add").click(function() {
$counter++;
$("#ipblock").append('<input type="text" name="inputip" id="inputip'+$counter+'" size="22" /></br>');
});
$("#del").click(function() {
$("#inputip'+$counter+'").remove();
$counter = parseFloat(counter) - 1;
});
The full demo can be found here http://jsfiddle.net/felix001/fQBNE/26/ . I can see via firebug that the inputs have the correct id`s. But when I try to remove it in both jquery and via the firebug console it fails to find the div (??).
Any one able to point me in the right direction.
Thanks,
Upvotes: 0
Views: 234
Reputation: 75993
You've got a couple errors in your code:
$counter = 0;
$("#add").click(function() {
$counter++;
//I removed the `<br />` tag and added a bit of CSS because if you remove the <input /> tags the <br /> tags added with them remain
$("#ipblock").append('<input type="text" name="inputip" id="inputip'+$counter+'" size="22" />');
});
$("#del").click(function() {
//this just makes sure there is actually an element to select before trying to select it
if ($counter) {
//use double quotes to start and stop the string here
$("#inputip"+$counter).remove();
//make sure to refer to `$counter` and not `counter`
$counter = $counter - 1;
}
});
Here is a demo: http://jsfiddle.net/fQBNE/29/
I added this CSS so that the <br />
tag wasn't necessary in your .append()
call:
/*This will put each input on its own line*/
#ipblock > input {
display:block;
}
Another way to accomplish this without a $counter
variable is to select the last input
element in the #del
click event handler:
$("#add").click(function() {
//notice no ID is needed
$("#ipblock").append('<input type="text" name="inputip" size="22" />');
});
$("#del").click(function() {
//first try to select the last inputip element
var $ele = $('#ipblock').children('input[name="inputip"]').last();
//only proceed if an element has been selected
if ($ele.length) {
//and now remove the element
$ele.remove();
}
});
Here is a demo: http://jsfiddle.net/fQBNE/31/
Upvotes: 2