2

I think there may be a new way to sort them without an attribute but I'm not getting it to work properly. Who can help me understand why?

Initially I create an array, I put the various elements in the correct order.

var order = [4,3,2,7,5,0,1,6,8];
var i = 0;

$.fn.formordina = function(selector){
    (selector ? this.find(selector) : this).parent().each(function(){
       
$(this).children(selector).sort(function(){
			return order[i++];
        }).detach().appendTo(this);
    });

    return this;
};

$(".form-action ol").formordina('li');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="form-action">
<ol>
<li>banana</li>
<li>apple</li>
<li>tomato</li>
<li>kiwi</li>
<li>pear</li>
<li>peach</li>
<li>lemon</li>
<li>ginger</li>
<li>orange</li>
</ol>

</div>

2
  • 1
    Not sure what your trying to accomplish here. .sort() can use a compare function, yet it's expecting -1, 0, or 1 to be returned. Please clarify your request. Commented Jun 12, 2019 at 1:00
  • This question might be what you are looking for? stackoverflow.com/questions/46781765/… Commented Jun 12, 2019 at 1:54

1 Answer 1

2

This might help you some. If you have a specific Sort order you want for the list, you may want to pass it in as an Option. Then collect the Items, organize the, flush the current list, and replace them with the new order.

$.fn.formordina = function(options) {
  console.log("Options", options);
  var listItems = this.find(options.items);
  var newList = {};
  $.each(options.order, function(k, v) {
    newList[k] = listItems.eq(v - 1)[0];
  });
  $(this).html("");
  console.log(newList);
  $(this).append(newList);
};

$(function() {
  $(".form-action ol").formordina({
    items: "> li",
    order: [4, 3, 2, 7, 5, 0, 1, 6, 8]
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="form-action">
  <ol>
    <li>banana</li>
    <li>apple</li>
    <li>tomato</li>
    <li>kiwi</li>
    <li>pear</li>
    <li>peach</li>
    <li>lemon</li>
    <li>ginger</li>
    <li>orange</li>
  </ol>
</div>

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.