简体   繁体   中英

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?

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');
});

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>

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