views:

373

answers:

2

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 would like them to retain their original position in the list order, even if the list is missing some original options. This is solely for the purpose of making the list more convenient for the user.

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

What would be the best way to implement this?

A: 

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.

szupie
A: 

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)

function init(selectId) {
    var s = document.getElementById(selectId);
    select_defaults[selectId] = new Array();
    select_on[selectId] = new Array();
    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 new = (to_add) : 1 : 0;
    if (old != new) {
        select_on[selectId][num] = new;
        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
    var next = 0;
    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[next] = select_defaults[selectId][i];
            next++;
        }
    }
}
DVK
Thanks a lot. I used a similar technique.
Rob