简体   繁体   中英

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

 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>

First solution:

You can do it this way:

var emptyOption = $("#select1 option").filter(function() {
                     return $.trim( $(this).val() ) == '';
                  });
var $options = emptyOption.prevAll().addBack().clone();
$('#select2').append($options);

JSFiddle: http://jsfiddle.net/inanda/uosvokdr/2/

Second solution:

If you can add a class to the options you want to copy, you can do it the following way.

HTML

<select id="select1">
    <option value="A" class="copy">option A</option>
    <option value="B" class="copy">option B</option>

    <option value="" class="copy">=============</option>
    <option value="AA">option AA</option>
    <option value="BB">option BB</option>

</select>

<select id="select2">
</select>

Javascript:

var $options = $("#select1 > option.copy").clone();

$('#select2').append($options);

Working JsFiddle: http://jsfiddle.net/inanda/m2qd177u/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM