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
<input type="text" name="name1" id="1" value="1" class="order">
<input type="text" name="name2" id="2" value="2" class="order">
<input type="text" name="name3" id="3" value="3" class="order">
<input type="text" name="name4" id="4" value="4" class="order">
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 > +previousId){
var plus = +duplicate - 1;
$("#"+duplicate).val(plus);
}else if(+previousVal < +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.