I am practicing jquery , by appending an removing input ,i succeded appending in input field but not been able to remove appended input field. i am also confused with parent() in my code.
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#add').click(
function(){
$('#a').append('<div><input type="text" name="ingre[]"><button class="remo">remove</button></div>');
});
});
$(document).ready(function(){
$(".remo").click(function(){
//alert('ok');
$(this).parent('.remo').remove();
});
});
</script>
</head>
<body class="ancestors">
<button id="add">Add</button>
<div id='a'>
<input type="text" >
</div>
</html>
Removing will not work, as you are attaching the event to all current elements that exist with the class .remo
. When you click Add a new element is created that does not have the handler bound, so it will not remove anything. The solution for this is event delegation, replace this:
$(".remo").click(function(){
$(this).parent('.remo').remove();
});
With this:
$("#a").on('click', '.remo', function(){
$(this).closest('div').remove();
});
$(document).ready(function(){ $('#add').click(function(){ $('#a').append('<div><input type="text" name="arr[]"><button class="remo">remove</button></div>'); }); $('#a').on('click', '.remo', function(){ $(this).parent().remove(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body class="ancestors"> <button id="add">Add</button> <div id='a'> <input type="text" > </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.