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!

5
  • I'm voting to close this question as off-topic because it is a duplicate of stackoverflow.com/questions/203198/… Commented Aug 6, 2015 at 5:32
  • 1
    how? It is completely different. My question is the function I was writing on the page load and it is not calling. Commented Aug 6, 2015 at 5:34
  • How you are using page variable? Commented Aug 6, 2015 at 5:35
  • Because from the script you have provided the delete_contact elements are created dynamically Commented Aug 6, 2015 at 5:36
  • 1
    So the question is exactly a duplicate of stackoverflow.com/questions/203198/… Commented Aug 6, 2015 at 5:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try:

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

1 Comment

$(function() { }); is another way of writing $(document).ready(function() {}); So, its basically is same as OP's code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.