javascriptjqueryhtml-selectcopyingjquery-ui-selectmenu

In JQuery, how do I copy a subset of select options from one select menu to another?


I'm using JQuery 1.11.1. I have two select menu elements, one containing options like

<select id="select1">
    <option value="A">option A</option>
    <option value="B">option B</option>
    ...
    <option value="">=============</option>
    <option value="AA">option AA</option>
    <option value="BB">option BB</option>
    ...
</select>

How do I copy the options up to and including the option with the "=============" text to the second select menu (let's say the second select menu has id='select2').

Thanks, - Dave


Solution

  • var option, count = -1;
    while ((option = $('#select1 option')[++count]).value != "")
    {
      $(option).clone().appendTo('#select2');
    }
    $($('#select1 option')[count]).clone().appendTo('#select2'); //for the '=====' one
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="select1">
        <option value="A">option A</option>
        <option value="B">option B</option>
        <option value="">=============</option>
        <option value="AA">option AA</option>
        <option value="BB">option BB</option>
    </select>
    
    <select id="select2">
    </select>