0

i am working with select 2, and i have data coming from ajax in json format.

View:

<select class="form-control qual_id" multiple>
    <option value="">-Select Degree-</option>
    <option value="1">SSC</option>
    <option value="2">HSC</option>
    <option value="3">BBA</option>
    <option value="4">MBA</option>
</select>

Ajax:

var defaultValue = 1,2 // (it can be one id or two ids)

$(`.qual_id option[value=${defaultValue}]`).attr('selected', true);

select2:

<script type="text/javascript">
$('.qual_id').select2({
  width: 'resolve',
  maximumSelectionLength: 2
});
</script>

if i remove multiple from select tag and and do it without select2 with one id, it is working fine, but how can i do it by selecting multiple values in select.

Console:

Uncaught Error: Syntax error, unrecognized expression: .qual_id option[value=1,2]

Fayakon
  • 1,173
  • 4
  • 23
  • 48

2 Answers2

2

I answered a similar question few months ago. You can refer to it from Dynamically add item to jQuery Select2 control that uses AJAX.

To answer your question, consider this example.

for(let i=0; i<jsonResponse.length; i++) {
    $(".qual_id").each(function() {
            if($(this).val() == jsonResponse[i]) {
            // select the option
        }
    });
}
$('.qual_id').trigger('change'); 

What you are looking for is .trigger() method. Refer Select2 Docs

Digvijay
  • 7,836
  • 3
  • 32
  • 53
0
var defaultValue = [1,2];
$(`.qual_id`).val(defaultValue);

This should set values 1 and 2 to be selected by default.