Reputation: 43
I'm new to jQuery.
Would you guys know why the .remove()
doesn't work for the rows that are added using the add
button? It works otherwise for the already existing elements such as <li>One</li>
.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.more').click(function(){
html_frag='<li>XXX<input type="submit" value="Remove" class="testing" /></li>';
$('ul li:last').after(html_frag);
return false;
});
});
$(document).ready(function(){
$('.testing').click(function(){
$(this).remove();
return false;
});
});
</script>
</head>
<body>
<ul>
<li>
One
<input type="submit" value="Remove" class="testing" />
</li>
</ul>
<input type="submit" value="Add" class="more" />
</body>
</html>
Upvotes: 4
Views: 883
Reputation: 10896
try this ,it doesn't work because you are creating element dynamically, for dynamically created element use on or live of jquery.
$("body").on("click", ".testing", function(event){
$(this).remove();
return false;
});
Upvotes: 0
Reputation: 79830
Because the newly added elements doesn't exist on DOM when you bind that handler. Try using delegated events like below,
$(document).ready(function(){
$(document).on('click', '.testing', function(){
$(this).remove();
return false;
});
});
Upvotes: 3