select 2 selected value code example
Example 1: select2 clear options
Remove the selected options :
-----------------------------
$('#mySelect2').val(null).trigger('change');
============================================
Completly remove the select2 initialization :
--------------------------------------------
$('#payment_method').html('').select2({data: [{id: '', text: ''}]});
Example 2: get value select 2
//get selected value
$('#mySelect2').find(':selected').val();
Example 3: select2 dropdown with option to add new item
$('#select2')
.select2()
.on('select2:open', () => {
$(".select2-results:not(:has(a))").append('<a href="#" style="padding: 6px;height: 20px;display: inline-table;">Create new item</a>');
})
Example 4: html select multiple selected values
var values = $('#select-meal-type').val();
Example 5: select2 multiple selected values
in_array($value, $array)
Example 6: select 2 select a value
SELECT2 V4 :
============
For select2 v4 you can append directly an option/s as follow:
<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
<option value="TheID" selected="selected">The text</option>
</select>
Or with JQuery:
---------------
var $newOption = $("<option selected='selected'></option>").val("TheID")
.text("The text")
$("#myMultipleSelect2").append($newOption).trigger('change');
other example :
---------------
$("#myMultipleSelect2").val(5).trigger('change');