tags:

views:

264

answers:

2

I have a javascript method which handles removing from one select box to another. The code runs as follows :

 function moveAllOptions(formName, selectId1, selectId2) {

     var sourceSelect = eval("document." + formName + "." + selectId1);
     var destSelect = eval("document." + formName + "." + selectId2);

     for (var i = 0; i < sourceSelect.length; i++) {  

         var optionText = sourceSelect.options[i].text;
         var optionValue = sourceSelect.options[i].value;

         for (var j = 0; j < destSelect.length; j++) {
             if (destSelect.options[j].value == optionValue) {
                 destSelect.options[j].value = null;
             }
         }

     }

 }

But I found a problem like when it encounters duplicate values it is not deleting all the values .For eg: in the view source I have

value="139">Customer Service<
value="231">Customer Service<
value="231">Customer Service<
value="231">Customer Service<
value="231">Customer Service<

In this case it removes only two objects from my left hand box. Is there any way to remove duplicate objects also.One way I could think is create an two array objects(Two Dimensional), pass all the values in left hand side to one array then iterate to another array and finally pass again to normal options.

+1  A: 

Well, first of all the eval to hunt elements is horrible. There are far better ways of doing this starting with getElementById.

As to your actual problem, again there are simpler native ways to do this: the add and remove methods of the select object (reference). Try this method to start with.

function transferOptions(A, B)
{
    var a = document.getElementById(A);
    var b = document.getElementById(B);

    while(a.options.length)
    {
     var x = a.options[0]; //store the value
     a.remove(0); //remove it from the DOM
     b.add(x); //reinsert it (adds to end of list)
    }
}

transferOptions('select1','select2') //usage
annakata
A: 
     for (var j = 0; j < destSelect.length; j++) {
         if (destSelect.options[j].value == optionValue) {
             destSelect.options[j].value = null;
         }
     }

Let's say the first item matched. You set destSelect.options[0].value to null, which effectively removes the first option from the list. Next you check destSelect.options[1], which is actually the third option in the original list. The second option has just become first, and occupies destSelect.options[0].

The way to avoid this problem is to go backwards, starting with the last item in the list and working up to the first.

     for (var j = destSelect.length-1; j >=0; j--) {
         if (destSelect.options[j].value == optionValue) {
             destSelect.options[j].value = null;
         }
     }
Patrick McElhaney