Select2 초기화 - Select2 chogihwa

select2를 이용하여 셀렉 박스를 만들고, 특정 버튼 클릭시 선택항목 초기화를 하고 싶었다.

그러나, value를 찍어보면 초기화가 된 것으로 보이나, 화면에는 여전히 첫번째 element가 선택되어 있었다.

해결방법을 찾아서 기록한다.

// 인터넷에 검색하면 나오는 방식
$("#셀렉박스ID").val(null).trigger('change');

// 위 방식이 작동하지 않을때
$('#셀렉박스ID').html('').select2({data: [{id: '', text: ''}]});

저작자표시비영리변경금지

How do I set the placeholder on value reset by select2. In my example If locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder. This script is resetting the value but won't show the placeholder

$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});

Creating new options in the dropdown

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control:

var data = {
    id: 1,
    text: 'Barn owl'
};

var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');

The third parameter of new Option(...) determines whether the item is "default selected"; i.e. it sets the selected attribute for the new option. The fourth parameter sets the options actual selected state - if set to true, the new option will be selected by default.

Create if not exists

You can use .find to select the option if it already exists, and create it otherwise:

// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
    $('#mySelect2').val(data.id).trigger('change');
} else { 
    // Create a DOM Option and pre-select by default
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');
} 

Selecting options

To programmatically select an option/item for a Select2 control, use the jQuery .val() method:

$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

You can also pass an array to val make multiple selections:

$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

Select2 will listen for the change event on the <select> element that it is attached to. When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.

Preselecting options in an remotely-sourced (AJAX) Select2

For Select2 controls that receive their data from an AJAX source, using .val() will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching. This is further complicated by server-side filtering and pagination - there is no guarantee when a particular item will actually be loaded into the Select2 control!

The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:

// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

Notice that we manually trigger the select2:select event and pass along the entire data object. This allows other handlers to access additional properties of the selected item.

Clearing selections

You may clear all current selections in a Select2 control by setting the value of the control to null:

$('#mySelect2').val(null).trigger('change');