Thursday, March 31, 2011

Remove / Delete jQuery droppable item

I have a simple drag and drop feature using jQuery,
I have it so that when you add a certain class it will insert a certain input field for that class.
I cannot figure out, however, how to remove an item already dropped?
I just want a nice little x or something next to each element dropped to remove it from the drop box.

Original Script without X button.




            <script>
          $(function() {
                   $( "#catalog" ).accordion();
                   $( "#catalog li" ).draggable({
                             appendTo: "body",
                             helper: "clone"
                   });
                   $( "#cart ol" ).droppable({
                             activeClass: "ui-state-default",
                             hoverClass: "ui-state-hover",
                             accept: ":not(.ui-sortable-helper)",
                             drop: function( event, ui ) {
                                      $( this ).find( ".placeholder" ).remove();
                                      var el=$("<li>"+ui.draggable.text()+"</li>").appendTo(this);
                             }
                   });
          });
          </script>

Script with X button.
            <script>
          $(function() {
                   $( "#catalog" ).accordion();
                   $( "#catalog li" ).draggable({
                             appendTo: "body",
                             helper: "clone"
                   });
                   $( "#cart ol" ).droppable({
                             activeClass: "ui-state-default",
                             hoverClass: "ui-state-hover",
                             accept: ":not(.ui-sortable-helper)",
                             drop: function( event, ui ) {
                                      $( this ).find( ".placeholder" ).remove();
                                      var el=$("<li>"+ui.draggable.text()+"</li>&nbsp;<a href='#'>[x]</a>").filter('a').click(function(){el.remove()}).end().appendTo(this);
                             }
                   });
          });
          </script>



Reference: Experts-exchange,JqueryUI

2 comments:

  1. Just what I was looking for, thanks!
    I noticed however, that the [x] often shows on the next line (the li forces a line break?). If you change the filter to a find you can place the href in the li element, and the click still works on it

    ReplyDelete
  2. Hi.
    Can you please let me know how I can revert back to placeholder after I hit [x]. Right now if I x all the items from the list I cannot drag a new item to it.

    ReplyDelete