Torque
Torque

Reputation: 23

Order <li> elements by id from array

I've used Jquery's sortable() to create an array that is saved to a database. The array contains the li id's of all li items in the ul. It is based on a drag n drop function.

<script>
      $(document).ready(function () {
          $('ul').sortable({
              axis: 'y',
              stop: function (event, ui) {
                  let data = $(this).sortable('toArray');
                  $('span').text(data);
                  $("#HiddenSortOrder").val(JSON.stringify(data))
                  console.log(data);
              }
          });
      });
</script>

The array it produces looks like this:

["13","14","16","15","","1","2","3","4","5","6","7","8","9","10","11","12","17","18","19","20","21","22","23","24","25","26","27","46","52",""]

I am trying to use this array to set the order of a list on another page. The li items look like this:

<li class="ui-state-default" id="1"><a href="linkOfSomething.php">nameOfSomething</a></li>

So far I've found/come up with:

$data[] = $sortOrderArray;
    <script>
        var sorted = $data[];
        sorted.forEach(function(id) {
            $("#" + id).appendTo("#sortable")
        })
    </script>

Or something like:

array.forEach(function(item) {
  var li = document.createElement("li");
  var text = document.createTextNode(item);
  li.appendChild(text);
  document.getElementById("myUl").appendChild(li);
});

I am however very unsure how to properly implement this. And if I am on the right track to begin with. Any suggestions?

Upvotes: 0

Views: 154

Answers (1)

Floeske
Floeske

Reputation: 110

Easiest way is to let PHP handle your order when loading the page. If not possible, because you'll only have the values in an array, it can be done by jQuery.

Do you have the jQuery code into the html/php page? Then you can do something like:

    <script>
        var sorted = <?= $sortOrderArray; ?>
        sorted.forEach(function(id) {
            $("#" + id).appendTo("#sortable")
        })
    </script>

I wouldn't recommend this because I preferably do not want JS/jQuery in my HTML/PHP.

Upvotes: 1

Related Questions