0

I have following js code

var page = '<div class="row delete_contact">
              <div class="col-xs-6 contact_item>
                <label class="control-label col-xs-2" for="id">ID:</label>
                <div class="controls col-xs-3">
                 <input class="form-control id" name="id" value="' + id +'">
                </div>
                <a href="javascript:void(0)" class="delete_contact_details control-label">
                   <span class="delete_contact_details control-label col-xs-1 glyphicon glyphicon-trash">
                   </span>
                </a>
             </div>
            </div>';

when we click on 'delete' image, it has to delete the full row(div). I tried following while page loading

$(function() {
   $('.delete_contact_details').on( "click", function() {
       $(this).closest('.delete_contact').remove();
   });
});

But it is not calling the below code. Anyone please help!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Futuregeek
  • 1,900
  • 3
  • 26
  • 51

2 Answers2

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.

Its seems you are dynamically generating elements, use Event Delegation using .on() delegated-events approach.

$(function() {
   $(document).on( "click", '.delete_contact_details', function() {
       $(this).closest('.delete_contact').remove();
   });
}); 

In place of document you should use closest static container.

Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Try:

$(document).ready(function() {
   $('.delete_contact_details').click(function() {
       $(this).closest('.delete_contact').remove();
   });
});
Rajan Goswami
  • 769
  • 1
  • 5
  • 17
  • `$(function() { });` is another way of writing `$(document).ready(function() {});` So, its basically is same as OP's code – Satpal Aug 06 '15 at 05:47