select2 4.0.3 预设值

 时间:2026-02-16 14:42:14

1、按照select2 的说明很容易就可以使用select2, 单选,多选都不是问题。但是如果使用预设值呢? 就是 select2 初始化后自动帮我们选定一个或者多个值, 改如何做呢?

2、当数据源不是 ajax时, 可以使用下面的方法设定预设值

$('#mySelect2').val('US'); 

$('#mySelect2').trigger('change')

3、当数据源是 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) {

    // 官网上使用ajax 来获得要预设的值, 我是直接使用页面上的隐藏域的值

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

           }

      });

}

select2 4.0.3 预设值

select2 4.0.3 预设值

4、下面的代码是我的实例

select2 4.0.3 预设值

  • select2的简单实用
  • 如何利用select2下拉搜素框设置其默认值
  • select2.js 如何引用
  • select2multiple多选设置默认值
  • 如何利用select2下拉框插件方法限制选框项个数
  • 热门搜索
    煜怎么读 拼音 宝塔糖怎么吃 肛门痒痒怎么回事 怎么保护嗓子 开机密码怎么设置 貂绒毛衣怎么洗 怎么选股票 小孩吓着了怎么叫魂 步阳防盗门怎么样 假睫毛怎么卸