duddosai duddosai - 21 days ago 7
Javascript Question

Multi select onchange event jquery

I'm creating a form. I have two fields, 1. default value field and 2. preview field. 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:

$("#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?

Answer

You said you are using select2 so execute like this:

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