Method for sorting numbers from user input I have an input with numbers 1, 2, 3, 4 and I want to change the order of this number dynamically according to users input. You can find my code below and also a running example here.

HTML

&lt;input type="text" name="name1" id="1" value="1" class="order"&gt;
&lt;input type="text" name="name2" id="2" value="2" class="order"&gt;
&lt;input type="text" name="name3" id="3" value="3" class="order"&gt;
&lt;input type="text" name="name4" id="4" value="4" class="order"&gt;


jQuery

var myArray = new Array();    
        $(".order").each(function() {
            myArray[$(this).attr('id')] = $(this).val();

        });//array to use when id and value are equal

    $('.order').live('change', function(){
            previousVal = $(this).val();
            previousId = $(this).attr('id');
            });//on change get this value as static to use later

    $('input.order').on('blur', function() {
    var idofnewvalue = $(this).attr('id');
    var newvalue = $(this).val();
    $(".order").each(function(){
            if (newvalue == $(this).val()) {
                    if(idofnewvalue != $(this).attr('id')){
                    var duplicate = $(this).val();
                        if(+previousVal &gt; +previousId){
                            var plus = +duplicate - 1;
                            $("#"+duplicate).val(plus);

                        }else if(+previousVal &lt; +previousId){
                            var plus = +duplicate + 1;
                            $("#"+duplicate).val(plus);
                        }else if(+previousVal == +previousId){
                            for ( var key in myArray) {

                                if (myArray.hasOwnProperty(key)) {
                                    $("#"+key).val(key);

                                  }
                                }

                        }

                    }
                    $("#"+duplicate).trigger("blur");//triggers blur event untill done
            }
        });
    });


The above code changes the value of the input according to users input.

For example, if the input is 1 2 3 4 and the user changes 4 to be 2, then the result will be 1 3 4 2.  If the user changes 2 to be 4 then the result will be 1 4 2 3. 

Please tell me what you think about the above code.
Interesting question,

I cant understand why you would need this functionality. It does not seem to sort at all, but in same cases it will remove dupes.

This code is so bad, you should first use the built in tools in JsFiddle and then come back.



Click TidyUp first, your JavaScript indenting is all over the place.
Then click JsHint, every red dot on the left hand side indicates 1 problem, there are many lines with multiple problems, so you will have to do this exercise multiple times.