JQuery select2 从列表中的选项设置默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16969666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:10:19  来源:igfitidea点击:

JQuery select2 set default value from an option in list?

javascriptjqueryhtml-selectjquery-select2

提问by user857276

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

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

回答by krishgopinath

One more way - just add a selected = "selected"attribute to the selectmarkup and call select2on it. It must take your selected value. No need for extra JavaScript. Like this :

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

Markup

标记

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

JavaScript

JavaScript

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

See fiddle : http://jsfiddle.net/6hZFU/

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

Edit:(Thanks, Jay Haase!)

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

If this doesn't work, try setting the valproperty of select2to null, to clear the value, like this:

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

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

After this, it is simple enough to set valto "Whatever You Want".

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

回答by rajesh_kw

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

You should actually do this...intialise and then set the value..well this is also the way it worked for me.

你实际上应该这样做......初始化然后设置值......这也是它对我有用的方式。

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

回答by user857276

One way to accomplish this is...

实现这一目标的一种方法是...

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

So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".

所以基本上你首先初始化插件然后使用'val'参数指定默认值。实际值取自指定选项,在本例中为 #1。所以从这个例子中选择的值将是“bar”。

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

Hope this is useful to someone else.

希望这对其他人有用。

回答by avebone

The above solutions did not work for me, but this code from Select2's own website did:

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

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

Webpage found here

网页在这里找到

Hope this helps for anyone who is struggling, like I was.

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

回答by Wishmaster

For 4.xversion

对于4.x版本

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

to select value with INDEX

INDEX选择值

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

to select nothing (show placeholder if it is)

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

回答by Brain90

Came from the future? Looking for the ajax source default value ?

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

You're welcome.

别客气。

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

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

回答by Fahad Bhuyian

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

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

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

回答by Aniket Thakur

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.

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

回答by Ajeet Lakhani

For ajax select2 multiple select dropdown i did like this;

对于 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

回答by charu joshi

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