title: Jquery populate optgroup for second selectbox dynamically
body: <p>I have a very long list of options in two multiple select box, I want to populate dynamically the options for <code>select_B</code> based on <code>select_A</code>, for instance:</p>
  
  <p>I multiple select opt1 and opt2 from <code>select_A</code>, <code>select_B</code> will show the options which is optgroup with <code>id=sub1</code> and <code>id=sub2</code> only, if I deselect opt1 and select opt3 from <code>select_A</code>, <code>select_B</code> will remove optgroup <code>sub1</code> and remain <code>sub2</code> and <code>sub3</code>, and so on with flexibility of control. </p>
  
  <pre><code>&lt;select id="select_A" multiple="multiple" size="10"&gt;
      &lt;optgroup label="group 1"&gt;
          &lt;option value="opt1" id="main1"&gt;opt1&lt;/option&gt;
          &lt;option value="opt2" id="main2"&gt;opt2&lt;/option&gt;
      &lt;optgroup label="group 2"&gt;
          &lt;option value="opt3" id="main3"&gt;opt3&lt;/option&gt;
  &lt;/select&gt;
  
  &lt;select id="select_B" multiple="multiple" size="10"&gt;
      &lt;optgroup label="opt1" id="sub1" style="display:none;"&gt;
          &lt;option value="1A"&gt;1A&lt;/option&gt;
          &lt;option value="1B"&gt;1B&lt;/option&gt;
  
      &lt;optgroup label="opt2" id="sub2" style="display:none;"&gt;
          &lt;option value="2A"&gt;2A&lt;/option&gt;
          &lt;option value="2B"&gt;2B&lt;/option&gt;
  
      &lt;optgroup label="opt3" id="sub3" style="display:none;"&gt;
          &lt;option value="3A"&gt;3A&lt;/option&gt;
          &lt;option value="3B"&gt;3B&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>I already have a solution for hiding optgroup in Chrome and IE from <a href="http://hceint.wordpress.com/2011/04/09/hiding-option-groups-optgroups-in-chrome-and-internet-explorer-with-jquery/" rel="nofollow">here</a>: </p>
  
  <pre><code>&lt;script&gt;
  $(document).ready(function() {
      $.fn.hideOptionGroup = function() {
          $(this).hide();
          $(this).children().each(function(){
          $(this).attr("disabled", "disabled").removeAttr("selected");
      });
  
      $(this).appendTo($(this).parent());
  
      }
  
      $.fn.showOptionGroup = function() {
          $(this).show();    
          $(this).children().each(function(){
          $(this).removeAttr("disabled");
      });
  
          $(this).prependTo($(this).parent());
          $(this).parent().animate({scrollTop:0},0);
      }
  
  
  
      $("#sub1,#sub2").showOptionGroup();
      $("#sub1,#sub2").hideOptionGroup();
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>Please help and thanks.</p>