[英]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. 从用户的角度来看,如果有人选择“红色” (值= 1)和“棕色” (值= 5)选择英文,我想要“rubrum” (值= 1)和“rufum” (值= 5)出现选择拉丁文选择。
For <input>
tags, this works: 对于
<input>
标签,这适用于:
$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.val( $(this).val() );
Sadly, this omits <select>
tags. 遗憾的是,这省略了
<select>
标签。
I found many ways to copy items, but can't find a way to copy actual selection. 我找到了许多复制项目的方法,但找不到复制实际选择的方法。
Fiddle here: http://jsfiddle.net/e53aJ/8/ 在这里小提琴: 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标记,你提供了所有
option
值为1
,应按如下顺序排列:
<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>
$('select[name="english"]').on('change', function () {
$('select[name="latin"]').val(this.value);
});
<select>
elements have a property selectedIndex
that indicates which of their options is selected. <select>
元素具有selectedIndex
属性,指示selectedIndex
了哪些选项。
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. 如果你得到
selectedIndex
之一的<select>
,然后设置selectedIndex
其他的<select>
到,你应该得到你正在寻找的结果。
However, if your <select>
accepts multiple selections (as your question implies), then it's a bit more tiresome. 但是,如果您的
<select>
接受多个选择(正如您的问题所暗示的那样),那么它会更加无聊。 You have to loop through the <option>
elements and check each one to see whether it's selected
property is true. 您必须遍历
<option>
元素并检查每个元素以查看它的selected
属性是否为true。
(This is why jQuery's popular: the JavaScript DOM interface frequently sucks .) (这就是jQuery流行的原因:JavaScript DOM界面经常糟透了 。)
$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.attr('selectedIndex', $(this).attr('selectedIndex'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.