I have 6 text fields in vertical alignment in a form with values corresponding to it's position. Each text field has a fruit name associated to it which aren't editable (the editable text fields are like serial numbers, if you may)
See JSFIDDLE URL
1 Apple
2 Banana
3 Cranberry
4 Date
5 Elderberry
6 Fennel
respectively. The user can edit and change (only the number, the fruit names are not editable) their values between 1 to 6 (I have a separate javascript function that won't let the user to input anything other than positive integers and not above the maximum count). I want to write a javascript/jquery function that will sort the numbers by following methodology:
Suppose the user changes value 3 to 5, it means the textbox with value 3 is moved to 5th position. This means the values 4 and 5 are pushed up to values 3 and 4 respectively (like a pop and insert in a random access array). So now the new values will be
1 Apple
2 Banana
5 Cranberry <-- user edited this from 3 to 5
3 Date <-- Javascript changed this
4 Elderberry <-- Javascript changed this
6 Fennel
Notice that the value 3 is in the 4th position and the value 4 is in the 5th position and the values 1,2 and 6 remain unaffected.
Now once again if the value 4 (now corresponding to Elderberry) is changed to 1, we apply the same logic and the output after javascript sorting will look like this
2 Apple
3 Banana
5 Cranberry
4 Date
1 Elderberry <-- user changed value from 4 to 1
6 Fennel
Now when the user saves and reloads the page, the items and their corresponding index gets written into the database and now will look like this,
1 Elderberry
2 Apple
3 Banana
4 Date
5 Cranberry
6 Fennel
Thanks in advance. Any suggestion or help of any kind is appreciated!
Code that I tried:
function sort(oldnumber, newnumber) {
var widget = $('#id'+oldnumber); //assuming the text boxes are id1, id2, ...
if(oldnumber < newnumber) {
for(var i = oldnumber+1; i <= newnumber; i++) {
$('#id'+i).val(i-1);
}
}
else {
for(var i = oldnumber-1; i >= newnumber; i++) {
$('#id'+i).val(i+1);
}
}
}