Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top