jqueryjquery-droppable

jQuery Droppable - Dont remove Original CSS class of <li> Tag after dropping


I am using jQuery UI Droppable plugin...

Somehow, my Draggable <li> element Class is getting removed after dropping. :(

How can I maintain the same CSS class for <li> tag after dropping the element

AFter dropping the <li class="one">Item 1</li> to Cart Area, I want to keep the same class to the <li> element as <li class="one">Item 1</li> where currently it is getting removed automatically.

Please check the Code Below...

HTML

<div id="products">
  <h2>Drag</h2>
  <div id="catalog">
      <ul>
        <li class="one">Item 1</li>
        <li class="two">Item 2</li>
        <li class="three">Item 3</li>
        <li class="four">Item 4</li>
        <li class="five">Item 5</li>
        <li class="six">Item 6</li>
      </ul>
  </div>
</div>

<div id="cart">
  <h2>Drop Here...</h2>
  <div class="ui-widget-content">
    <ol>
      <li class="placeholder">Add your items here</li>
    </ol>
  </div>
</div>

jQuery

$(function() {
    $( "#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();
            $( "<li></li>" ).html( ui.draggable.html() ).appendTo( this );
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $( this ).removeClass( "ui-state-default" );
        }
    });
});

FIDDLE



Solution

  • Change this line:

    $( "<li></li>" ).html( ui.draggable.html() ).appendTo( this );    
    

    to this:

    $(ui.draggable).appendTo(this);
    

    or

    $(ui.draggable).clone().appendTo(this);
    

    or

    $( "<li class='"+$(ui.draggable).attr("class")+"'></li>" ).html( ui.draggable.html() ).appendTo( this );    
    

    Your code is creating a new li.

    Demo: http://jsfiddle.net/kux7x16y/5/