Bilal Hussain Bilal Hussain - 6 months ago 22
Javascript Question

unable to move multiple items in the list up or down in jquery

I have following code in jquery code to move the list item up or down in the list on the click of up and down buttons.

$("#btn-move-up").click(function () {
$item = $(".highlight");
$before = $item.prev();
$item.insertBefore($before);
});

//onclick of move down button, move the item down in the list
$("#btn-move-down").click(function () {
$item = $(".highlight");
$after = $item.next();
$item.insertAfter($after);
});


The code works fine for the single item but if you select multiple items, it start behaving unexpectedly.the working fiddle here.
Can someone please point out the mistake in my code or any other better solution?

Answer

Need to select the first item of the list before inserting before, and last item before inserting after. Else it would insert before or after for every item highlighted:

$("#btn-move-up").click(function() {
  $item = $(".highlight");
  $before = $item.first().prev();
  $item.insertBefore($before);
});

//onclick of move down button, move the item down in the list
$("#btn-move-down").click(function() {
  $item = $(".highlight");
  $after = $item.last().next();
  $item.insertAfter($after);
});


$('ul').on("click", "li", function(e) {
  if ($(this).hasClass('highlight')) {
    $(this).removeClass('highlight');
  } else {

    $(this).addClass('highlight');

  }
  e.stopPropagation();
});
.highlight {
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn-move-up" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Up"><i class="fa fa-arrow-up"></i>Up</button>

<button type="button" id="btn-move-down" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Down"><i class="fa fa-arrow-down"></i>Down</button>

<ul id="fields">
  <li>Ist</li>
  <li>2nd</li>
  <li>3rd</li>
  <li>4th</li>
</ul>