简体   繁体   中英

How to copy selection from one select to another?

I have two select elements, with same number of options, and same values for these options, but different (translated) texts.

How can I copy selection from one to another?

From user perspective, if someone will select "red" (value=1) and "brown" (value=5) in English select, I want "rubrum" (value=1) and "rufum" (value=5) to appear selected in Latin select.

For <input> tags, this works:

$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.val( $(this).val() );

Sadly, this omits <select> tags.

I found many ways to copy items, but can't find a way to copy actual selection.

Fiddle here: http://jsfiddle.net/e53aJ/8/

Edit: I'd love it to work both for single and multiselect, if possible. I know at first I did not reflect that in my fiddle, sorry.

I saw your html markup there you supplied all option values to 1 that should be in order like below:

Html:

    <div class=".common-identifier">
        <select name="english" class=".common-identifier">
            <option value=1>red</option>
            <option value=2>green</option>
            <option value=3>yellow</option>
            <option value=4>blue</option>
            <option value=5>brown</option>
        </select>
        <select name="latin" class=".common-identifier">
            <option value=1>rubeum</option>
            <option value=2>viride</option>
            <option value=3>flavus</option>
            <option value=4>caeruleo</option>
            <option value=5>brunneis</option>
        </select>
    </div>

jQuery:

$('select[name="english"]').on('change', function () {
   $('select[name="latin"]').val(this.value);
}); 

Fiddle

<select> elements have a property selectedIndex that indicates which of their options is selected.

If you get the selectedIndex of the one <select> , then set the selectedIndex of the other <select> to that, you should get the result you're looking for.

However, if your <select> accepts multiple selections (as your question implies), then it's a bit more tiresome. You have to loop through the <option> elements and check each one to see whether it's selected property is true.

(This is why jQuery's popular: the JavaScript DOM interface frequently sucks .)

$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.attr('selectedIndex', $(this).attr('selectedIndex'));

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