Clément Andraud
Clément Andraud

Reputation: 9269

jQuery, add draggable to append object

I am in the success handler of an ajax request like :

    $.ajax({
        type: "POST",
        url: "{{ path('getevents') }}",
        data: {start: start, end : end},
        success: function (data) {

            for ( var i = 0; i < data['rdv'].length; i++ ) {
                var divRdv = '<div>My div</div>';
                $('myElement').append(divRdv);

                $(divRdv).draggable(); // THIS DOESN'T WORK
            }
        },
        error: function (xhr, status, error) {
          console.log(xhr.responseText);
      }
  });

So, in a loop, i need to create a div divRdv, append this div to myElement, and after that, i want this div draggable.

How can i do ?

I'm trying to add draggable to each div, one by one, there is a way to add draggable to multiple element in one time ?

Upvotes: 1

Views: 1331

Answers (2)

A. Rama
A. Rama

Reputation: 912

That's because you're already added that code in the DOM by appending it. But since it wasn't a jQuery object, it was just added as HTML and your variable is just holding text, not a jquery object identifying an element of the dom.

So, when you do the draggable call, you're doing it on an entirely new jquery (and thus, dom) object and not on the one you have added.

Do this:

var divRdv = $('<div>My div</div>');
$('myElement').append(divRdv);

divRdv.draggable(); // THIS SHOULD WORK :)

Upvotes: 6

Rupert
Rupert

Reputation: 1639

You could add a class to your draggable divs and then call draggable on all of them, like this:

$.ajax({
        type: "POST",
        url: "{{ path('getevents') }}",
        data: {start: start, end : end},
        success: function (data) {
            for ( var i = 0; i < data['rdv'].length; i++ ) {
                var divRdv = '<div class="draggable">My div</div>';
                $('myElement').append(divRdv);
            }
            $('.draggable').draggable();
        },
        error: function (xhr, status, error) {
          console.log(xhr.responseText);
      }
  });

Upvotes: 1

Related Questions