jquery - Sort text fields based on position javascript -
i have 6 text fields in vertical alignment in form values corresponding it's position. each text field has fruit name associated aren't editable (the editable text fields serial numbers, if may)
see jsfiddle url
1 apple 2 banana 3 cranberry 4 date 5 elderberry 6 fennel
respectively. user can edit , change (only number, fruit names not editable) values between 1 6 (i have separate javascript function won't let user input other positive integers , not above maximum count). want write javascript/jquery function sort numbers following methodology:
suppose user changes value 3 5, means textbox value 3 moved 5th position. means values 4 , 5 pushed values 3 , 4 respectively (like pop , insert in random access array). new values
1 apple 2 banana 5 cranberry <-- user edited 3 5 3 date <-- javascript changed 4 elderberry <-- javascript changed 6 fennel
notice value 3 in 4th position , value 4 in 5th position , values 1,2 , 6 remain unaffected.
once again if value 4 (now corresponding elderberry) changed 1, apply same logic , output after javascript sorting this
2 apple 3 banana 5 cranberry 4 date 1 elderberry <-- user changed value 4 1 6 fennel
now when user saves , reloads page, items , corresponding index gets written database , this,
1 elderberry 2 apple 3 banana 4 date 5 cranberry 6 fennel
thanks in advance. suggestion or of kind appreciated!
code tried:
function sort(oldnumber, newnumber) { var widget = $('#id'+oldnumber); //assuming text boxes id1, id2, ... if(oldnumber < newnumber) { for(var = oldnumber+1; <= newnumber; i++) { $('#id'+i).val(i-1); } } else { for(var = oldnumber-1; >= newnumber; i++) { $('#id'+i).val(i+1); } } }
with insertbefore
method can reorder rows. reindexing done after insertion. here simple demonstration: http://jsfiddle.net/cgb2qlj2/
$('.row .num').on('change', function (evt) { var num = $(this).val(); $(this).parent().insertbefore($('.row:nth-child('+num+')')); $('.row .num').each(function (i, input) { $(input).val(i + 1); }); });
edit: without changing order of rows, it's bit more complicated conditions, gets job done. note have save previous value correct behaviour.
updated fiddle: http://jsfiddle.net/cgb2qlj2/3/
updated code:
var val = $(input).val(); if (input != self) { if (val > old && val <= num) { $(input).val(+val - 1); } else if (val < old && val >= num) { $(input).val(+val + 1); } }
Comments
Post a Comment