-2

I have problem here with a button. So I want to clone items from one list to another one. I also want to add a button when passed to the other list. The problem appears when I click the button. Nothing happens. Item does not get removed. Do you have any idea why that's happening?

jQuery:

    $( function() {
    $( "#sortable1").sortable({
        connectWith: ".connectedSortable",
        items: "li:not(.ui-state-disabled)",
        remove: function(event, ui) {
            ui.item.clone().append( "<button class='cancelBut'>Cancel</button>" ).appendTo('#sortable13');
            $(this).sortable('cancel');
        }
    }).disableSelection();

    $( "#sortable13").sortable({
        connectWith: ".connectedSortable",
        items: "li:not(.ui-state-disabled)"
    }).disableSelection();

       $( ".cancelBut" ).click(function() {
        //$(this).parent().remove();
        alert("It works");
    });
    });

HTML:

    <div id="items" style="display: none">
    <ul id="sortable1" class="connectedSortable">
        <li class="ui-state-default ui-state-disabled">Items</li>
        <li class="ui-state-default"><p>Item 1</p></li>
    </ul>
</div>

<ul id="sortable13" class="connectedSortable">
    <li class="ui-state-default ui-state-disabled">Drag Here</li>
</ul>

Im new to jQuery so sorry if the answer is obvious and thanks for help :)

Jakub Badacz
  • 63
  • 1
  • 7
  • You need to use a delegated click handler as the `.cancelBut` element isn't in the DOM when the page loads, eg: `$(document).on('click', '.cancelBut', function() { ...`. See the duplicate question for more info – Rory McCrossan Dec 09 '16 at 23:35
  • @RoryMcCrossan Thank you it worked! – Jakub Badacz Dec 09 '16 at 23:46

1 Answers1

0

Use event delegation.

$('.body').on('click', '.cancelBut', function() {

});

The event handles are only attached to the elements that are present in the DOM the way you have defined the click event.

In your case you are running into the exact scenario where the handlers are not bound. By using event delegation, the event will bubble to the element to which the click is bound ( body in this case) and will invoke the click of the cloned element.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105