How to restore the order of an (incomplete) selection list in the original order?

I have two selection lists between which you can move the selected options. You can also move parameters up and down in the right list.

When I move the parameters back to the left list, I would like them to keep their original position in the list, even if some initial parameters are not in the list. This is done solely to make the list more user friendly.

I am currently defining an array with the original Selectload onload list.

What would be the best way to implement this?

+4
source share
2 answers

You can save the original order in the array, and when pasting back, determine which last element in the array precedes the one you want to insert, and corresponds to what is currently in the selection list. Then insert after that.

The best solution is to simply save the entire old array and re-fill each insert with the desired elements as follows (warning: code not verified)

function init(selectId) { var s = document.getElementById(selectId); select_defaults[selectId] = []; select_on[selectId] = []; for (var i = 0; i < s.options.length; i++) { select_defaults[selectId][i] = s.options[i]; select_on[selectId][i] = 1; var value = list.options[i].value; select_map_values[selectId][value] = i if you wish to add/remove by value. var id = list.options[i].id; // if ID is defined for all options select_map_ids[selectId][id] = i if you wish to add/remove by id. } } function switch(selectId, num, id, value, to_add) { // You can pass number, value or id if (num == null) { if (id != null) { num = select_map_ids[selectId][id]; // check if empty? } else { num = select_map_values[selectId][value]; // check if empty? } } var old = select_on[selectId][num]; var newOption = (to_add) : 1 : 0; if (old != newOption) { select_on[selectId][num] = newOption; redraw(selectId); } } function add(selectId, num, id, value) { switch(selectId, num, id, value, 1); } function remove(selectId, num, id, value) { switch(selectId, num, id, value, 0); } function redraw(selectId) { var s = document.getElementById(selectId); s.options.length = 0; // empty out for (var i = 0; i < select_on[selectId].length; i++) { // can use global "initial_length" stored in init() instead of select_on[selectId].length if (select_on[selectId][i] == 1) { s.options.push(select_defaults[selectId][i]); } } } 
+5
source

I would assign ascending values ​​to the elements so that you can insert the element back into the right place. The assigned value remains with the item no matter what list it is on.

0
source

Source: https://habr.com/ru/post/1307501/


All Articles