Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reorder a HTML list with jQuery after a button click?

I would like to return a list of numeric elements after clicking the "Click me!" with jQuery only.

For example, the follow values:

55.5
456.5
.54
32.2

Should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.54
32.2
55.5
456.5

Code:

$(function() {
  $('.btn').on('click', function() {
    $('input').keyup(function() {
      var start = $(this).index('input');
      var target = $(this).val() - 1;
      if (target < start) $(this).parent().insertBefore($('li').eq($(this).val() - 1));
      if (target > start) $(this).parent().insertAfter($('li').eq($(this).val() - 1));
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="ItemList">
  <li>some number 1
    <input id="Text1" type="number" value="32.2" />
  </li>
  <li>some number 2
    <input id="Text2" type="number" value="456.5" />
  </li>
  <li>some number 3
    <input id="Text3" type="number" value="55.5" />
  </li>
  <li>some number 4
    <input id="Text4" type="number" value=".54" />
  </li>
</ul>

<button class='btn'>
      Click me!
    </button>

But, not work. I managed to get it to work, but the function only recognizes the first digit. The others she ignores.

>Solution :

If you want to reorder the list using the input value inside the "li" you can try like this: (check the fiddle: https://jsfiddle.net/v1oskqg0/)

$(".btn").on("click", function() {
    $("#ItemList li").each(function(index) {
        var input_value = $(this).find('input').val();
        $(this).data('order', input_value);
    })
    $("#ItemList li")
      .sort((a,b) => $(a).data("order") - $(b).data("order"))
      .appendTo("#ItemList");
});

First, I stored the value from the input field into a data attribute on the li element and then I sorted the elements on btn click.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading