0

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();
});
Dhia
  • 10,119
  • 11
  • 58
  • 69
its.me.chand
  • 95
  • 1
  • 1
  • 9
  • Try $("#mydiv").html(""); Can you post some of you html as well? – Jesper Højer Jun 09 '16 at 11:08
  • when i press the rmvbtn button,it is not even going to the function specified for it when clicked. – its.me.chand Jun 09 '16 at 11:12
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – John Jun 09 '16 at 11:14

1 Answers1

1

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>
Satpal
  • 132,252
  • 13
  • 159
  • 168