Jquery Draggable multi item

I have basic javascript code.

I made a drag-and-drop system with inventory.

My question is: The current drag-and-drop system works but only for one item.

I want all items to be draggable, how can I do this?

My Code ?s here:

 <div class="row">
                        <?php 
                        $query = $dbh->query("SELECT * FROM goods", PDO::FETCH_ASSOC);
                            if ( $query->rowCount() ){
                                 foreach( $query as $row ){  ?>
                                    <div id="draggable" class="col-md-2">
                                        <img src="<?php echo baseURL.'images/'.$row['image']; ?>" data-id="<?php echo $row['id']; ?>">
                                    </div>

                            <?php  } } ?>
                    </div>`

Javascript code;

$( function(){
    var id = $('img').data('id');

    $("#draggable").draggable({

    });

    $("#droppable").droppable({

      over: function(event,ui) {
        $('#draggable').addClass("gbr");  
      },

      drop:function(event,ui) {
        $(this)
          .find("p")
          .html("Dropped!");
          jQuery.ajax({
            type: "POST",
            data: "id=" +id,
            url: "postgoods.php"
        });
      },
      out:function(event,ui) {
          $('#draggable').removeClass("gbr")
          $('#droppable').addClass('overee')
          .find("p")
          .html("Drop Here");
      }

    });

 });

Answers 1

  • First this is not basic javascript. $() is typically jQuery, which is a javascript library.

    Secondly, you are repeating the id on every one of the elements. Ids in HTML are expected to be unique. Which is why it is only finding one to initialize the plugins on.

    Change your logic to use a class, class="draggable", and then select it when you initialize, $('.draggable')


Related Articles