简体   繁体   English

多选onchange事件jQuery

[英]Multi select onchange event jquery

I'm creating a form. 我正在创建一个表格。 I have two fields, 1. default value field and 2. preview field. 我有两个字段,即1.默认值字段和2.预览字段。 Both are multiselect fields. 两者都是多选字段。 The user will add the options to the multiselect manually. 用户将手动将选项添加到多选。 Whenever the user chooses an option in the default value, the same value should be shown as selected in the preview field. 每当用户在默认值中选择一个选项时,都应显示与在预览字段中选择的相同的值。 When the user removes one option, the same option should be unselected. 当用户删除一个选项时,应取消选择相同的选项。 This is how I've written the onchange event for this multiselect: 这就是我为此多重选择编写onchange事件的方式:

$("#MultiSelect_DefaultValues").change(function() {
          alert($(this).val());
          $("#MultiSelect_Preview").val($(this).val());
        });

I get the correct value in the alert. 我在警报中得到正确的值。 But, in the preview field, there is no reaction. 但是,在预览字段中,没有任何反应。 All the options available in the default value field are available in the preview field too. 默认值字段中可用的所有选项在预览字段中也可用。 But, the options selected in the default value field is not selected in the preview field. 但是,未在预览字段中选择在默认值字段中选择的选项。 What's wrong with this? 这怎么了 What should I change, so that the changes in the default field reflects in the preview field too? 我应该更改什么,以便默认字段中的更改也反映在预览字段中?

You said you are using select2 so execute like this: 您说您正在使用select2,所以请像这样执行:

$("#MultiSelect_DefaultValues").change(function () {
   alert($(this).val());
   var prevSelect = $("#MultiSelect_Preview").select2();
   prevSelect.val($(this).val()).trigger('change');
});

The values on the option tags need to match for this, if I'm understanding correctly what you're trying to achieve that is. 如果我正确理解了您要实现的目标,则选项标签上的值需要与此匹配。

eg 例如

 $("#MultiSelect_DefaultValues").change(function() { console.log($(this).val()); $("#MultiSelect_Preview").val($(this).val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="MultiSelect_DefaultValues" multiple> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <select id="MultiSelect_Preview" multiple> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> 

you can use this code 您可以使用此代码

<script>
$("#MultiSelect_DefaultValues").change(function () {
    $('select[id="MultiSelect_Preview"]').find('option[value=' + $(this).val() + ']').attr("selected", true);
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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