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

0

Speak, all right? So I have a problem ...

I have a "sort by" button, in this case, higher price and lower price. What I need to do is sort the elements of a <li> list by its value attribute. For example: <li value="200"> . It is worth remembering that what the list contains can not influence the ordination. <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);
        }

Thank you in advance, a strong hug friends!

- > DEMO < -

    
asked by anonymous 04.06.2016 / 03:59

1 answer

3

You can do 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><ulid="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>
    
04.06.2016 / 04:33