Sort a list <ul> by the "value" attribute of <li>?

Asked

Viewed 964 times

0

Talk personal, all right? So I got a problem...

I have a "sort by" button, in this case, of higher price and lower price. What I need to do is sort the elements of a list <li> for his attribute value. For example: <li value="200">. Remember that what the list contains cannot influence the ordering. <li value="200">Não importa o que há aqui</li>. I have a working demo, but it turns my attr('value') into text.. I’m not sure what to do...

<ul id="list">
    <li value="20">doesnmatter1</li>
    <li value="10">doesntmatter2</li>
    <li value="5">doesntmatter3</li>
    <li value="30">doesntmatter4</li>
    <li value="519">doesntmatter5</li>
</ul>

<button id="ordena-menor">Sort</button>
<button id="ordena-maior">Sort</button>



$(function() {
            $('#ordena-menor').click(function() {
                var liContents = [];
                $('ul li').each(function() {
                    liContents.push(parseInt($(this).attr('value'), 10));
                });
                liContents.sort(numOrdDesc);
                $('ul li').each(function() {
                    $(this).text(liContents.pop());
                });
            });

            $('#ordena-maior').click(function() {
                var liContents = [];
                $('ul li').each(function() {
                    liContents.push(parseInt($(this).attr('value'), 10));
                });
                liContents.sort(numOrdCres);
                $('ul li').each(function() {
                    $(this).text(liContents.pop());
                });
            });
        });

        function numOrdDesc(a, b) {
            return (b - a);
        }

        function numOrdCres(a, b) {
            return (a - b);
        }

I thank you already, a strong hug friends!

-> DEMO <-

1 answer

3


You can do it like this:

Example:

$('#ordena-menor').click(function() {
  $("#list li").sort(numOrdDesc).appendTo('#list');
});

$('#ordena-maior').click(function() {
  $("#list li").sort(numOrdCres).appendTo('#list');
});


function numOrdDesc(a, b) {
  return ($(b).val()) < ($(a).val()) ? 1 : -1;
}

function numOrdCres(a, b) {
  return ($(b).val()) > ($(a).val()) ? 1 : -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<ul id="list">
  <li value="20">doesnmatter1</li>
  <li value="10">doesntmatter2</li>
  <li value="5">doesntmatter3</li>
  <li value="30">doesntmatter4</li>
  <li value="519">doesntmatter5</li>
</ul>

<button id="ordena-menor">Sort</button>
<button id="ordena-maior">Sort</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.