Reputation: 483
<div class="form-group">
<select class="form-control js-example-basic-multiple"
name="regular[]" id="regular" multiple="multiple" required>
<option value="History">History</option>
<option value="Political Science">Political Science
</option>
<option value="Economics">Economics</option>
<option value="Education">Education</option>
<option value="Philosophy">Philosophy</option>
<option value="Elective Assamese">Elective Assamese
</option>
<option value="Elective Hindi">Elective Hindi</option>
<option value="Arabic">Arabic</option>
<option value="Mathematics">Mathematics</option>
<option value="Linguistics">Linguistics</option>
</select>
</div>
This is my select2 input.
$(document).ready(function () {
$('#regular').select2({
placeholder: 'Select any two from the options',
maximumSelectionLength: 2,
});
});
I've loaded the select2.js here. and I am fetching data from ajax call.
options = data.regular.split(",");
this option
has 3 values, I want to select the first two from the array.
Hence My code is..
option = [options[0],options[1]];
$("#regular").val(option).trigger('change');
Now the options are showing in the list. But if I click and select from the input, everything resets and I have to select again. And if without changing anything I want to submit, the field shows required.
Upvotes: 2
Views: 148
Reputation: 1332
here the code works because the values from the server are identical to two of the values of the Option elements
So maybe your problem is the option string is not already existing
, Also it's case sensitive so "arabic" !== "Arabic" arabic will not work
either change in option tag or change the value string from JSON response
Hope this Helps 😘
$(document).ready(function() {
mySelect = $('#regular').select2({
placeholder: 'Select any two from the options',
maximumSelectionLength: 2
});
options = 'Economics,Arabic,Education'.split(',');
option = [options[0],options[1]];
//simulate ajax using timeout
setTimeout(function() {
mySelect.val(option).trigger("change");
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="form-group">
<select class="form-control js-example-basic-multiple" name="regular[]" id="regular" multiple="multiple" required>
<option value="History">History</option>
<option value="Political Science">Political Science
</option>
<option value="Economics">Economics</option>
<option value="Education">Education</option>
<option value="Philosophy">Philosophy</option>
<option value="Elective Assamese">Elective Assamese
</option>
<option value="Elective Hindi">Elective Hindi</option>
<option value="Arabic">Arabic</option>
<option value="Mathematics">Mathematics</option>
<option value="Linguistics">Linguistics</option>
</select>
</div>
Upvotes: 1