its.me.chandu its.me.chandu - 5 months ago 7
jQuery Question

removing appended code is not working

I have appended checkboxes on a button click it works fine but after appending removing those by another button click is not at all working.I need someone to checkout and help.



$(".btn").on('click', function(){
$('#Locations').append('<div id="mydiv">' +
'<input type="button" value="-" class="rmvbtn">' +
'<input type="checkbox" name="myCheckbox" />' +
$(".txt").val() +
"</br>............</br>" +
'</div>');
});

$(".rmvbtn").click(function(){
$('#mydiv').remove();
});




Answer

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

General Syntax

$(document).on('event','selector',callback_function)

As per your code

$('#Locations').on("click", ".rmvbtn", function(){
    $('#mydiv').remove();
});

$(".btn").on('click', function(){
    $('#Locations').append('<div id="mydiv">' +
                       '<input type="button" value="-" class="rmvbtn">' +
                       '<input type="checkbox" name="myCheckbox" />' +
    $(".txt").val() +
     "</br>............</br>" +
     '</div>');
});

$('#Locations').on("click", ".rmvbtn", function(){
    $('#mydiv').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Create</button>
<div id="Locations"></div>

Comments