1
votes

I have a select2 element like this:

$(document).ready(function () {
    $('.select2').select2({
        multiple: true
    });
});
.select2{
width:100%
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select name="test" class="select2" multiple='multiple'>
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
    <option value='D'>D</option>
</select>

For some reason, when I add value, it is not shown as selected, but upon posting data from form, I receive all values form this select. Example:

Options C and D are selected, in options dropdown they are highlighted as selected, but in "main" element, they are not.

Once I save the form and page re-renders, select2 is now showing the selected values. See this picture.

If I try to remove any value using the X, it will not get removed from "main" element, but it would be deselected from options and again, form will submit correct values.

I tried to google but did not manage to find any help. The version of Select2 I am using is 4.0.5. Bootstrap v3 and jQuery 1.11.0 is also included in the page. I have tried changing order or including CSS and JS, but nothing seem to make any difference. Applying bootstrap theme for select2 did not help as well.

Any idea what could be wrong?

1
why are you using multiple: true in jquery, already you have declared in select tag as multiple="multiple" and check is there any display: none property applied for li tag - charan kumar

1 Answers

0
votes

It seems to work fine.

$(document).ready(function () {
    $('.select2').select2({
        multiple: true
    });
    
    $('button').on('click',function(){
      alert($('.select2').val());
    });
});
.select2{
width:150px;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<select name="test" class="select2" multiple='multiple'>
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
    <option value='D'>D</option>
</select>
<button>get values</button>