Tuesday, May 07, 2013

Copy/Move options from one Select element to another


The above picture tells the problem we are going to solve now. It is two select elements with 4 buttons. The functions of all the buttons are described below.

1. First button moves multiple selected options from left to right select element
2. Second button moves all options from left to right select element
3. Third button moves multiple selected options from right to left select element
4. Fourth button moves all options from right to left select element

We would use the same techniques which were discussed in my previous posts. We would write some functions against the "click" events of those buttons. Now check out the HTML below..

<table border='0'>
 <tr>
  <td>
    <select id='selectBox1' size='10' multiple='multiple' style='width:100px'>
   <option value='apr'> Aprilia </option>
    <option value='duc'> Ducati </option>
    <option value='hro'> Hero </option>
    <option value='hnd'> Honda </option>
    <option value='hyo'> Hyosung </option>
    <option value='kwk'> Kawasaki </option>
    <option value='suz'> Suzuki </option>   
    <option value='yam'> Yamaha </option>

    </select>
  </td>
  <td valign='middle'>
    <!-- FOUR BUTTONS -->
    <input type='button' onclick="move_selected('selectBox1','selectBox2')" value='>' style='width:30px'> <br />
     <input type='button' onclick="move_all('selectBox1','selectBox2')" value='>>' style='width:30px'> <br />
     <input type='button' onclick="move_selected('selectBox2','selectBox1')" value='<' style='width:30px'> <br />
     <input type='button' onclick="move_all('selectBox2','selectBox1')" value='<<' style='width:30px'> <br />

  </td>
  <td>
    <select id='selectBox2' size='10' multiple='multiple' style='width:100px'>
   
    </select>
  </td>
 </tr>
</table>


The select elements are having IDs 'selectBox1' and 'selectBox2'. We call two user-defined functions namely "move_selected" and "move_all". The "move_selected" function takes two parameters, source and target select elements. The second function works with same parameters. We have kept the second select element empty.

Moving selected options from one select element to another would involve following steps ..

a. Copy all selected options from source element to an array
b. Also copy index of items which has been selected and would be deleted after move
c. Next, create options for the target element from the array
d. Delete the moved items from source elements
e. Sort the Target element to keep it neat [Optional]

Moving all items from one to another involves following steps ..

a. Copy all options from source element to target directly
b. Delete the moved items from source elements
c. Sort the Target element to keep it neat [Optional]

Now check out the Javascript functions below which are quite self-explanatory.

<script type="text/javascript">

// Move Selected Items from one to other SelectBox
function move_selected( from, to )
{
  // Get the Select Elements
  var s = document.getElementById(from);
  var t = document.getElementById(to);
 
  // Put the selected elements in an array
  var opt = [];
  var to_be_deleted = [];
  var j = 0;
  var i = 0;
  for( i=0;i<s.options.length;i++)
  { 
    if( s.options[i].selected == true )
    {
      // Copy Value+TEXT for moving
      opt[ s.options[i].value ]  =  s.options[i].text;
     
      // Store the Index, for Deletion
      to_be_deleted[j] = i;
      j++;
    }
  }
 
  // Delete the selected Option from Source select element
  for( i=0;i<to_be_deleted.length;i++)
   s.options.remove( to_be_deleted[i] );
  
  // Iterate thorough all Saved option Value+Text
  // and Insert Into the Target Select element
  for( var key in opt )
  {
    // Create new Option
    var no = new Option( opt[key], key );
   
    // Insert
    t.options[ t.options.length ] = no;
  }
 
  // SORT the Target Select Element
  select_elem_sort(to);
}


// Move ALL Items from one to other SelectBox
function move_all( from, to )
{
  // Get the Select Elements
  var s = document.getElementById(from);
  var t = document.getElementById(to);
 
  // ITERATE Source Element's Option List
  var i = 0;
  for( i=0;i<s.options.length;i++)
  { 
      // Create new Option
      var no = new Option( s.options[i].text, s.options[i].value );
   
      // Insert
      t.options[ t.options.length ] = no;
  }
 
  // Delete All options from source Element
  s.options.length = 0;
 
  // SORT the Target Select Element
  select_elem_sort(to);
}

// This is for sorting the Option List
function select_elem_sort(t)
{
   
    // Get the TARGET Select element
    var s = document.getElementById(t);
   
    // Iterate through its options and create
    // a reference array with option VALUE:TEXT
    var opt_reference = [];
    var opt_text_arry = [];

    // Our copying starts from Index 0
    for( var i=0; i<s.options.length; i++)
    {
       // Store Option value and text to reference array
       opt_reference [ s.options[i].value ] = s.options[i].text ;
     
       // Store only the TEXT to the second array for sorting
       opt_text_arry[i] = s.options[i].text;
    }

    // Sort the Array Ascending
    opt_text_arry.sort( function(a, b) {
        if(a>b) return 1;
        if(a<b) return -1;
        return 0;
    } );

    var i=0;
    /// Iterate the array and Re-create options
    for(i=0; i<opt_text_arry.length; i++ )
    {
      var option_text = opt_text_arry[i];
   
      /// FETCH the corresponding option value
      /// against the option text
      var option_val = "";
      for( var key in opt_reference)
      {
         // Option Text matched
         if( opt_reference[key] == option_text )
         {
           option_val = key;
           break;
         }
      
      }

      // Create the new Option
      var opt = new Option( option_text, option_val);
   
      // Put the new option in the Options Array
      // of Select element. We are re-creating
      // new options from index 0 onwards
      s.options[i] = opt;
    }
}
</script>


The above code runs fine on all browsers including IE7 and IE8. 


You can find some more discussions on HTML Select element here

No comments: