我在 ERB 中有两个选择器。他们使用选择的插件:
<%= select_tag :provinces,
options_for_select(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{:multiple => true, class: 'chosen-select chzn-select',
:data => {:placeholder => 'Filter Provinces/States'}}
%>
<%= f.select :province_ids,
(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{ include_blank: true },
{multiple: true, data: {placeholder: 'Filter Provinces/States'} }
%>
我试图将选项从一个选择器复制到另一个选择器,同时保持所选选项仍处于选中状态,但它不起作用。这是我尝试过的 Javascript 函数:
var selectedVals = [];
$(".chzn-select").chosen().change(function() {
$("#provinces option:selected").each(function () {
console.log ("this value is " + ($(this).val()));
selectedVals.push($(this).val());
});
$("#education_plan_province_ids").empty();
for (var i = 0; i < selectedVals.length; i++) {
console.log (selectedVals[i] + " selected");
$("#education_plan_province_ids").append($("<option>" + selectedVals[i] + "</option>").attr('selected', true));
}
selectedVals = [];
});
除了attr('selected', true)
还有其他选择吗?
最佳答案
给你:
$(".chzn-select").chosen().change(function() {
$("#education_plan_province_ids").empty();
$("#provinces option:selected").each(function () {
$("#education_plan_province_ids").append($("<option>" + this.value + "</option>").prop('selected', true));
});
});
我在这里使用 prop
并删除了额外的数组(我认为不需要,但如果需要,您可以使用它)。另外,选项
的括号位置错误。
关于javascript - 将选定的选项附加到选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38513977/