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下拉框插件方法限制选框项个数
  • 热门搜索
    关于推广普通话的手抄报 科技改变生活手抄报 传染病防控手抄报 文明旅游手抄报 建军节手抄报内容 读书节手抄报图片 关于西游记的手抄报 生活中的小数手抄报 爱国诚信友善手抄报 水浒传手抄报图片大全