zee zee - 6 months ago 26
jQuery Question

Re-arrange Text Input fields based on Number entered by user

I have few inputs, and it comes with values from 1 to 100 in it, but user can alter those values. I have sorted my inputs in Ascending order. Now I want that each time user changes an input, they should be re-arranged in ascending order.
Here is my HTML template:

var sortedArray = $("div[class^='wrap_']").get().sort(function(a, b) {
var idx = parseInt($(a).find(".sort_by").val(),10);
var idx2 = parseInt($(b).find(".sort_by").val(),10);
return idx > idx2;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap_0">
<input class="sort_by" value="10"/>
<div class="wrap_1">
<input class="sort_by" value="3"/>
<div class="wrap_2">
<input class="sort_by" value="7"/>

Right now they appear as:
if user changes 3 to 12, I want my output to be automatically changed to:
7 10 12.
I want Jquery solutions only. Thanks in advance.


You can use the input event and apply the sort method on the parent div jQuery collection. Please note that I added class wrap so the divs can be easily selected. The code .trigger('input') ensures that the input (actually parent div) elements are sorted when the page loads.

$(function() {
    $('.sort_by').on('focusout', function() {
        var arr = $('div.wrap');
        arr = arr.sort(function(a,b) {
            return +$(a).find('.sort_by').val() - +$(b).find('.sort_by').val();
        $('body').append( arr );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_0 wrap">
    <input class="sort_by" value="10"/>
<div class="wrap_1 wrap">
    <input class="sort_by" value="3"/>
<div class="wrap_2 wrap">
    <input class="sort_by" value="7"/>