mokalovesoulmate mokalovesoulmate - 6 months ago 42
Javascript Question

jQuery Sortable prevent user to move child item to parent item

I have this list in HTML:

<ol class="sortable subcategory_item">
<li data-id="102">A</li>
<li data-id="111">B</li>
<li data-id="1712">GROUP A
<ol class="group_items">
<li data-id="105">GROUP MEMBER 1</li>
<li data-id="108">GROUP MEMBER 2</li>
<li data-id="109">GROUP MEMBER 3</li>
</ol>
</li>
<li data-id="110">C</li>
<li data-id="113">D</li>
</ol>


The problem is I am able to move items under
GROUP A
to their parent.

How can I prevent
GROUP MEMBER 1
,
GROUP MEMBER 2
and
GROUP MEMBER 3
(or items inside
<ol class="group_items">
to be moved above
GROUP A
?

I am currently using jquery-sortable plugin but I am okay if I have to switch using another plugin.

Thanks.

Answer

Here is the demo

$("#sortable").sortable({
  change: function(event, ui) {
    var currentClass = $(ui.placeholder)[0].classList[0];
    if (!$(ui.placeholder).prev().hasClass(currentClass) && !$(ui.placeholder).next().hasClass(currentClass))
      return false;
  }
});
$(".group_items").sortable();

$("#sortable").disableSelection();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sortable/0.9.13/jquery-sortable-min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<ol class="sortable subcategory_item" id="sortable">
  <li data-id="102" class="grp1">A</li>
  <li data-id="111" class="grp1">B</li>
  <li data-id="1712" class="grp1">GROUP A
    <ol class="group_items">
      <li data-id="105" class="grp">GROUP MEMBER 1</li>
      <li data-id="108" class="grp">GROUP MEMBER 2</li>
      <li data-id="109" class="grp">GROUP MEMBER 3</li>
    </ol>
  </li>
  <li data-id="110" class="grp1">C</li>
  <li data-id="113" class="grp1">D</li>
</ol>