3

I have a list of selected companies which looks like this:

<div id="selected_companies">
    <div class="company">
      <a>
        <div class="delete_company"></div>
        Company One
      </a>
    </div>
    <div class="company">
      <a>
        <div class="delete_company"></div>
        Company Two
      </a>
    </div>
</div>

I want to have "move" each .company div into a separate #deleted_companies div when one of the companies is clicked. I am doing this with jQuery:

$('#selected_companies .company a').on('click', function (e) {
        /* Getting the company */
        var company_id = $(this).prev().prop('value');
        $('.form').append('<input type="hidden" name="deleted_companies[]" value="'+ company_id +'" />');

        var parent = $(this).parent();

        parent.appendTo('#deleted_companies');
        $('#deleted_companies').slideDown(300);
});

When I click on one of the companies, the .company div moves into the desired div (#deleted_companies), but when I try to reach it within that div, it does not perform as expected. For example, this code does not work:

$('#deleted_companies .company a').on('click', function (e) {
    alert('This should work.');
});

So how do I make that alert work?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cgf
  • 3,369
  • 7
  • 45
  • 65

1 Answers1

6

Use delegation, try this

$('#deleted_companies').on('click', '.company a', function (e) {
    alert('This should work.');
});

This is basically saying to look at the #deleted_companies (which exists at the time your bind is created) for .company a which doesn't necessarily have to exist before this bind is created for it to work.

Smern
  • 18,746
  • 21
  • 72
  • 90
  • 2
    More about [direct vs. delegated event handlers](http://stackoverflow.com/q/8110934/578288) – Rory O'Kane Jul 02 '13 at 20:15
  • Genius! I have worked on this for hours now. I guess I just didn't know how to search for it. Thank you! – cgf Jul 02 '13 at 20:16
  • Awesome link, @RoryO'Kane, can't believe it was THIS simple. Thanks a bunch! – cgf Jul 02 '13 at 20:17