当前位置: 首页 > 工具软件 > Select2 > 使用案例 >

jQuery-select2 官方文档笔记(二)——较高级应用

夹谷硕
2023-12-01

select2官网:https://select2.org/

一、Search

单选select默认有一个search框。多选select没有明显的search框,但是在文本框中输入的时候具有搜索效果。

1. matcher

可以通过定义matcher来自定义search box的行为,当然这里的matcher只对local data有效。

function matchCustom(params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') {
      return data;
    }

    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') {
      return null;
    }

    // `params.term` should be the term that is used for searching
    // `data.text` is the text that is displayed for the data object
    if (data.text.indexOf(params.term) > -1) {
      var modifiedData = $.extend({}, data, true);
      modifiedData.text += ' (matched)';

      // You can return modified objects from here
      // This includes matching the `children` how you want in nested data sets
      return modifiedData;
    }

    // Return `null` if the term should not be displayed
    return null;
}

$(".js-example-matcher").select2({
  matcher: matchCustom
});
2. 分组matcher

只有第一级的对象会经过matcher方法处理,如果你需要处理的是一个分组的select,则需要通过遍历children数组来一个个match。
This example matches results only if the term appears in the beginning of the string:

function matchStart(params, data) {
  // If there are no search terms, return all of the data
  if ($.trim(params.term) === '') {
    return data;
  }

  // Skip if there is no 'children' property
  if (typeof data.children === 'undefined') {
    return null;
  }

  // `data.children` contains the actual options that we are matching against
  var filteredChildren = [];
  $.each(data.children, function (idx, child) {
    if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
      filteredChildren.push(child);
    }
  });

  // If we matched any of the timezone group's children, then set the matched children on the group
  // and return the group object
  if (filteredChildren.length) {
    var modifiedData = $.extend({}, data, true);
    modifiedData.children = filteredChildren;

    // You can return modified objects from here
    // This includes matching the `children` how you want in nested data sets
    return modifiedData;
  }

  // Return `null` if the term should not be displayed
  return null;
}

$(".js-example-matcher-start").select2({
  matcher: matchStart
});
3. 设置最短最长搜索词组长度(minimumInputLength & maximumInputLength)
$('select').select2({
  minimumInputLength: 3, // only start searching when the user has input 3 or more characters
  maximumInputLength: 20 // only allow terms up to 20 characters long
});
4. 最小搜索结果数设置(minimumResultsForSearch)
$('select').select2({
    minimumResultsForSearch: 20 // at least 20 results must be displayed
});
4. 单选select隐藏搜索框(minimumResultsForSearch)

minimumResultsForSearch值设置为-1,或者Infinity

$("#js-example-basic-hide-search").select2({
    minimumResultsForSearch: Infinity
});
5. 多选select隐藏搜索框

设置后select中只能选择,不能输入文本

$('#js-example-basic-hide-search-multi').select2();

$('#js-example-basic-hide-search-multi').on('select2:opening select2:closing', function( event ) {
    var $searchfield = $(this).parent().find('.select2-search__field');
    $searchfield.prop('disabled', true);
});

二、Programmatic control

1. 创建option
var data = {
    id: 1,
    text: 'Barn owl'
};

var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');

The third parameter of new Option(…) determines whether the item is “default selected”; i.e. it sets the selected attribute for the new option. The fourth parameter sets the options actual selected state - if set to true, the new option will be selected by default.

2. 不存在的情况下创建option
// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
    $('#mySelect2').val(data.id).trigger('change');
} else { 
    // Create a DOM Option and pre-select by default
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');
} 
3. js设置选中状态

单选select:

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

多选select:

$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.

4. 数据源为ajax的select2的选中状态

对于ajax源的select2来说,不能通过.val()设置预选中状态,因为在select2被打开或者用户开始搜索前,ajax请求根本不会被发送,所以根本就没有options,更无法设置预选中状态。
因此,处理这种情况的最简单办法就是把预选中的项目作为新项目添加进来。

The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:

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

Notice that we manually trigger the select2:select event and pass along the entire data object. This allows other handlers to access additional properties of the selected item.

5. 清空选择项
$('#mySelect2').val(null).trigger('change');
6. 获取选中值

方法1:

$('#mySelect2').select2('data');

返回一个js对象数组,包括选中项的所有properties/values。

方法2:

$('#mySelect2').find(':selected');

可以扩展<option>选项,通过data-*属性添加自定义数据。

$('#mySelect2').select2({
  // ...
  templateSelection: function (data, container) {
    // Add custom attributes to the <option> tag for the selected option
    $(data.element).attr('data-custom-attribute', data.customValue);
    return data.text;
  }
});

// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
7. 内置方法

(1)打开列表(open)

$('#mySelect2').select2('open');

(2)关闭列表(close)

$('#mySelect2').select2('close');

(3)检查列表是否已初始化

if ($('#mySelect2').hasClass("select2-hidden-accessible")) {
    // Select2 has been initialized
}

(4)去除select2特性(destroy)

$('#mySelect2').select2('destroy');

(5)解绑事件(.off)
去除select2特性后,只会去除自带的效果,自己手动绑定的事件,还需通过.off手动解绑。

// Set up a Select2 control
$('#example').select2();

// Bind an event
$('#example').on('select2:select', function (e) { 
    console.log('select event');
});

// Destroy Select2
$('#example').select2('destroy');

// Unbind the event
$('#example').off('select2:select');
8. 事件

(1)事件列表
当用户在select2上执行不同操作时,select2会触发不同的事件,用户能够监听这些事件,并且添加相应的处理。
用户也可以通过.trigger来手动触发这些事件。

EventDescription
changeTriggered whenever an option is selected or removed.
change.select2Scoped version of change. See below for more details.
select2:closingTriggered before the dropdown is closed. This event can be prevented.
select2:closeTriggered whenever the dropdown is closed. select2:closing is fired before this and can be prevented.
select2:openingTriggered before the dropdown is opened. This event can be prevented.
select2:openTriggered whenever the dropdown is opened. select2:opening is fired before this and can be prevented.
select2:selectingTriggered before a result is selected. This event can be prevented.
select2:selectTriggered whenever a result is selected. select2:selecting is fired before this and can be prevented.
select2:unselectingTriggered before a selection is removed. This event can be prevented.
select2:unselectTriggered whenever a selection is removed. select2:unselecting is fired before this and can be prevented.

(2)监听事件

$('#mySelect2').on('select2:select', function (e) {
  // Do something
});

(3)通过e.params.data获得Event Data

$('#mySelect2').on('select2:select', function (e) {
    var data = e.params.data;
    console.log(data);
});

(4)手动触发事件
你可以手动触发事件,而且还可以传递一些参数。

var data = {
  "id": 1,
  "text": "Tyto alba",
  "genus": "Tyto",
  "species": "alba"
};

$('#mySelect2').trigger({
    type: 'select2:select',
    params: {
        data: data
    }
});

(5)Limiting the scope of the change event
(6)Preventing events

 类似资料: