1<select id="lang" >
2 <option value="1">php</option>
3 <option value="2">asp</option>
4 <option value="3">java</option>
5</select>
6
7<script>
8 $("#lang").select2().select2('val','1');
9</script>
1$('#mySelect').select2({
2 data: ['one','two'],
3 tags: true
4});
5$('#mySelect').val(['one','two']).trigger('change')
1var options = [];
2$.each(dataReturn, function (i, obj) {
3 //console.log(i);
4 //console.log(obj);
5 options.push({
6 text: obj.NickName,
7 id: obj.NickName
8 });
9})
10$("#BeneType").empty().select2({
11 data: options
12});
1$('#select2')
2 .select2()
3 .on('select2:open', () => {
4 $(".select2-results:not(:has(a))").append('<a href="#" style="padding: 6px;height: 20px;display: inline-table;">Create new item</a>');
5})
6
1var initQuantitiesDropdown = function () {
2 var options = [];
3 var selectedFruit = $("#fruits").val();
4 $.each(pageData.products[selectedFruit].quantities, function (key, value) {
5 options.push({
6 text: value,
7 id: key
8 });
9 })
10 $("#quantities").empty().select2({
11 data: options
12 });
13};
14
15$("#fruits").select2().change(initQuantitiesDropdown);
16initQuantitiesDropdown();
1SELECT2 V4 :
2============
3For select2 v4 you can append directly an option/s as follow:
4
5<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
6 <option value="TheID" selected="selected">The text</option>
7</select>
8
9Or with JQuery:
10---------------
11
12var $newOption = $("<option selected='selected'></option>").val("TheID")
13 .text("The text")
14
15$("#myMultipleSelect2").append($newOption).trigger('change');
16
17other example :
18---------------
19
20$("#myMultipleSelect2").val(5).trigger('change');