Skip to content Skip to sidebar Skip to footer

How Can I Restore The Order Of An (incomplete) Select List To Its Original Order?

I have two Select lists, between which you can move selected options. You can also move options up and down in the right list. When I move options back over to the left list, I wou

Solution 1:

You can store the original order in an array, and when inserting back, determine what's the latest element in the array that precedes the one to be inserted AND matches what's currently in the select list. Then insert after that.

A better solution is to just store the old array whole and re-populate on every insertion with desired elements as follows (warning: code not tested)

functioninit(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.
    }
}

functionswitch(selectId, num, id, value, to_add) { // You can pass number, value or idif (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);
    }
}

functionadd(selectId, num, id, value) {
    switch(selectId, num, id, value, 1);
}

functionremove(selectId, num, id, value) {
    switch(selectId, num, id, value, 0);
}

functionredraw(selectId) {
    var s = document.getElementById(selectId);
    s.options.length = 0; // empty outfor (var i = 0; i < select_on[selectId].length; i++) { 
        // can use global "initial_length" stored in init() instead of select_on[selectId].lengthif (select_on[selectId][i] == 1) {
            s.options.push(select_defaults[selectId][i]);
        }
    }
}

Solution 2:

I would assign ascending values to the items so that you can insert an item back in the right place. The assigned value stays with the item no matter which list it's in.

Post a Comment for "How Can I Restore The Order Of An (incomplete) Select List To Its Original Order?"