Nice programing

JQuery select2는 목록의 옵션에서 기본값을 설정합니까?

nicepro 2021. 1. 10. 19:57
반응형

JQuery select2는 목록의 옵션에서 기본값을 설정합니까?


JQuery Select2 플러그인을 사용하여 선택 요소의 기본 / 선택 값을 설정할 수 있기를 원합니다.


한 가지 더 방법 selected = "selected"select마크 업에 속성을 추가 하고 호출 select2하는 것입니다. 선택한 값을 가져야합니다. 추가 JavaScript가 필요하지 않습니다. 이렇게 :

마크 업

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

자바 스크립트

$('select').select2(); //oh yes just this!

바이올린 참조 : http://jsfiddle.net/6hZFU/

편집 : (감사합니다, Jay Haase!)

그래도 작동하지 않으면의 val속성을 select2설정하여 null다음과 같이 값을 지우십시오.

$('select').select2("val", null); //a lil' bit more :)

그 후에로 설정하는 것은 간단 val합니다 "Whatever You Want".


이를 수행하는 한 가지 방법은 ...

$('select').select2().select2('val', $('.select2 option:eq(1)').val());

따라서 기본적으로 먼저 플러그인을 초기화 한 다음 'val'매개 변수를 사용하여 기본값을 지정합니다. 실제 값은 지정된 옵션 (이 경우 # 1)에서 가져옵니다. 따라서이 예제에서 선택한 값은 "bar"입니다.

<select class=".select2">
  <option id="foo">Some Text</option>
  <option id="bar">Other Text</option>
</select>

이것이 다른 사람에게 유용하기를 바랍니다.


$("#id").select2("val", null); //this will not work..you can try

이 작업을 실제로 수행해야합니다 ... 초기화 한 다음 값을 설정해야합니다.이 방법도 저에게 효과적입니다.

$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');

위의 솔루션은 저에게 효과적이지 않았지만 Select2 자체 웹 사이트의이 코드는 다음과 같이 작동했습니다.

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

여기에서 웹 페이지를 찾았습니다.

이것이 저처럼 어려움을 겪고있는 사람에게 도움이되기를 바랍니다.


대한 4.x의 버전

$('#select2Id').val(__INDEX__).trigger('change');

INDEX로 값을 선택하려면

$('#select2Id').val('').trigger('change');

아무것도 선택하지 않으려면 (있는 경우 자리 표시 자 표시)


미래에서 왔습니까? ajax 소스 기본값을 찾고 계십니까?

// 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
        }
    });
});

천만에요.

Reference: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2


Don't know others issue, Only this code worked for me.

$('select').val('').select2();

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

    $('select').select2("val",null);

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

ReferenceURL : https://stackoverflow.com/questions/16969666/jquery-select2-set-default-value-from-an-option-in-list

반응형