0

I have an ul called .products and inside of that are a bunch of li's called .product.

Each li has a data-id on them with the product's id in the database.

I'm building the functionality so that when a user clicks "move up" or "move down", that product will be moved up or down one slot in the list.

$('.move-up').click(function(event) {
  event.preventDefault();
  var shownFieldsArray = $.makeArray($('.products'));

  var currentIndex = $(shownFieldsArray).index($(event.currentTarget).parent());
  shownFieldsArray.move(currentIndex, (currentIndex - 1));

 // now I need to do something with the reordered shownFieldsArray

});

Move is a function (link to another SO answer with the function) on the Array prototype that takes an old value and a new value and moves things accordingly.

So my question is: How should I replace the value of $('.products') with the new, re-ordered list so the user can get visual confirmation? Should I remove the items and re-append them or is there something better like a replacement of .val()?

Community
  • 1
  • 1
Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151

2 Answers2

0

Since the two elements you want to swap are adjacent siblings there is no need to do any of the above. It's as easy as:

$('.move-up').click(function(event) {
  event.preventDefault();
  $(this).after($(this).prev());
});

What this does is insert the previous sibling (.prev) of the clicked item after the clicked item itself (.after). The previous sibling is an element already present in the DOM, so this clause in the documentation is relevant:

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved rather than cloned

Jon
  • 428,835
  • 81
  • 738
  • 806
0

For this I would make use of jQuery UI

sorting in jquery ui

With this you can easily re-order with what you already have for products, then when they save you just do something like.

var array = []
$('.products').each(function(){
  array.push($(this).attr('data-id');
});

This is just a fairly general example, I just feel from looking at your code that it seems you may be over complicating it. This way they can sort it as they want very easily.

The jQuery UI docs are fairly detailed and there is a lot you can do with it, nice and easy way to get some of the more time consuming JS functions out of the way.

Jordan Ramstad
  • 169
  • 3
  • 8
  • 37