Reputation: 140
New to javascript and jQuery, but I'm trying to dynamically add buttons and then remove them when they are clicked. If a button is there already (in the same class I am creating new buttons), it can be removed. If a new button gets added by the user, that button has no control. I also tried the .live
method that was mentioned in a similar post to no avail. Any help is appreciated. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> test </title>
<script src="jquery-1.6.2.js"></script>
<script>
/*
$(document).ready(function(){
$(".btn :button").click(function(){
$(this).remove();
});
*/
$(".btn :button").live("click", function(){
$(this).remove();
});
function add() {
// $(".btn").append("<button> new one </button>");
$("<button> new one </button>").insertAfter(".btn");
};
</script>
</head>
<body>
<div class="btn">
<button> test </button>
</div>
<br /><br />
<div class="adding">
<button onclick='add()'> add </button>
</div>
</body>
</html>
Upvotes: 3
Views: 21947
Reputation: 79032
$("button").on("click", function(){
$(this).remove();
});
or, if you want to remove the parent container as well:
$("button").on("click", function(){
$(this).parent().remove();
});
UPDATE:
If you only want buttons inside a specific div, try this:
$(".adding button").click(function() {
$('.adding').before('<div class="btn"><button>new button</button></div>');
});
$(".btn button").on("click", function() {
$(this).parent().remove();
});
Upvotes: 5
Reputation: 3721
You dont need a :
before button
selector
$(".btn button").live("click", function(){
$(this).remove();
});
Upvotes: 3