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:
.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.
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.