sourcetip

JQuery select2 set default value in list의 옵션에서 기본값을 설정하시겠습니까?

fileupload 2023. 11. 4. 13:15
반응형

JQuery select2 set default value in list의 옵션에서 기본값을 설정하시겠습니까?

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

한가지 방법만 더 추가하면 됩니다.selected = "selected"에 귀속시키다select마크업과 통화select2당신이 선택한 값을 가져야 합니다.추가 자바스크립트가 필요 없습니다.이와 같이:

마크업

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

자바스크립트

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

fiddle 참조 : http://jsfiddle.net/6hZFU/

편집: (고마워요, 제이 하세!)

이 방법이 작동하지 않으면 다음을 설정해 보십시오.val의 소유물.select2로.null, 값을 지우려면 다음과 같이 하십시오.

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

이 후에는 설정이 간단합니다.val로."Whatever You Want".

위의 해결책들은 저에게 효과가 없었지만, 셀렉트2의 자체 웹사이트에 있는 이 코드는 다음과 같이 했습니다.

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

웹 페이지가 여기에 있습니다.

이것이 저처럼 힘든 사람들에게 도움이 되기를 바랍니다.

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

당신은 정말로 이렇게 해야 합니다.초기화한 다음 값을 설정합니다.저도 이런 식으로 일했어요

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

이를 달성하기 위한 한가지 방법은...

$('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>

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

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

천만에요.

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

1단계: 빈칸을 하나 추가해야 합니다.option선택한 태그에 빈 값을 입력합니다.

2단계: 추가data-placeholder자리 표시자 값을 사용하여 선택 태그에서 속성

HTML

<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

jQuery

$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

오어

$('.select2').select2({
    placeholder: 'Custom placeholder text'
});

예.

var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');

여기 https://select2.org/programmatic-control/add-select-clear-items 에서 보실 수 있습니다.

쉬워요.예를 들어 기본값이 2인 옵션을 선택합니다.

HTML:

<select class="select2" id="selectBox">
   <option value="1">Some Text</option>
   <option value="2">Other Text</option>
</select>

자바스크립트:

$("#selectBox").val('2').trigger('change')

다른 사람들은 몰라요, 이 코드만 저한테 효과가 있었어요.

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

보통은 active를 사용하지만 select2에서는 selected="selected"로 변경됩니다.

Python/Flask 사용 예제

HTML:

<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
  {% for x in list%}
  <option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
  {% endfor %}
</select>

JQuery:

$(document).ready(function() {
        $('.js-example-basic-multiple').select2();
    });

    $(".js-example-theme-multiple").select2({
        theme: "classic",
        placeholder: 'Select your option...'
    });
    $('select').select2("val",null);

배열 데이터 소스를 사용하는 경우 아래와 같은 작업을 수행할 수 있습니다.

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

이는 데이터 세트 중 기본값으로 설정하려는 항목 하나에 selected라는 추가 속성이 있다고 가정하고 이를 사용하여 값을 설정합니다.

ajax의 경우 select2 multiple select 드롭다운을 선택하면 다음과 같습니다.

  //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

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

반응형