71

我希望能够使用 JQuery Select2 插件设置选择元素的默认/选定值。

4

14 回答 14

59

另一种方法 - 只需向标记添加一个selected = "selected"属性select并调用select2它。它必须采用您选择的值。无需额外的 JavaScript。像这样 :

标记

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

JavaScript

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

见小提琴:http: //jsfiddle.net/6hZFU/

编辑:(谢谢,杰伊哈斯!)

如果这不起作用,请尝试设置 to 的属性val,以清除该值,如下所示:select2null

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

val在此之后,设置为很简单"Whatever You Want"

于 2013-06-06T19:03:15.700 回答
34

上述解决方案对我不起作用,但 Select2 自己网站上的这段代码可以:

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

在这里找到的网页

希望这对像我一样挣扎的人有所帮助。

于 2017-06-28T21:15:50.497 回答
25
$("#id").select2("val", null); //this will not work..you can try

您实际上应该这样做...初始化然后设置值..这也是它为我工作的方式。

$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
于 2013-09-06T18:56:13.087 回答
23

实现此目的的一种方法是...

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

希望这对其他人有用。

于 2013-06-06T18:39:08.667 回答
13

对于4.x版本

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

INDEX选择值

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

不选择任何内容(如果是则显示占位符)

于 2017-12-19T07:43:13.113 回答
5

来自未来?寻找 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

于 2019-08-18T06:40:15.790 回答
2

例如

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

于 2021-09-25T04:28:15.463 回答
2

第 1 步:您需要option在您的选择标签中附加一个带有空白值的空白。

data-placeholder第 2 步:在带有占位符值的选择标记中添加属性

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'
});
于 2020-12-18T08:47:23.850 回答
0

通常我们通常使用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>

查询:

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

    $(".js-example-theme-multiple").select2({
        theme: "classic",
        placeholder: 'Select your option...'
    });
于 2021-09-11T03:03:38.647 回答
0

这很简单。例如,我想选择默认值为 2 的选项:

HTML:

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

Javascript:

$("#selectBox").val('2').trigger('change')
于 2022-01-12T06:26:42.347 回答
0

不知道其他问题,只有这段代码对我有用。

$('select').val('').select2();
于 2018-12-24T09:22:01.780 回答
-1

如果您使用的是数组数据源,您可以执行以下操作 -

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

这假设在您的数据集中,您要设置为默认值的一项具有称为 selected 的附加属性,我们使用它来设置值。

于 2017-12-10T16:26:17.823 回答
-1
    $('select').select2("val",null);
于 2016-06-21T10:45:38.217 回答
-2

对于 ajax select2 多选下拉菜单,我这样做了;

  //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
于 2016-01-15T11:50:32.410 回答