Select2 start with input field instead of dropdown

前端 未结 11 888
太阳男子
太阳男子 2020-12-08 06:44

I use the js library select2. This is a screenshot of what I have now:
Start:
\"enter

11条回答
  •  自闭症患者
    2020-12-08 07:34

    This is possible in Select2 4.0.0 with the new selection adapters. You can swap out the SingleSelection with a MultipleSelection (including any relevant decorators) and it should behave as expected.

    $.fn.select2.amd.require([
      'select2/selection/multiple',
      'select2/selection/search',
      'select2/dropdown',
      'select2/dropdown/attachBody',
      'select2/dropdown/closeOnSelect',
      'select2/compat/containerCss',
      'select2/utils'
    ], function (MultipleSelection, Search, Dropdown, AttachBody, CloseOnSelect, ContainerCss, Utils) {
      var SelectionAdapter = Utils.Decorate(
        MultipleSelection,
        Search
      );
      
      var DropdownAdapter = Utils.Decorate(
        Utils.Decorate(
          Dropdown,
          CloseOnSelect
        ),
        AttachBody
      );
      
      $('.inline-search').select2({
        dropdownAdapter: DropdownAdapter,
        selectionAdapter: SelectionAdapter
      });
      
      $('.dropdown-search').select2({
        selectionAdapter: MultipleSelection
      });
      
      $('.autocomplete').select2({
        dropdownAdapter: DropdownAdapter,
        selectionAdapter: Utils.Decorate(SelectionAdapter, ContainerCss),
        containerCssClass: 'select2-autocomplete'
      });
    });
    .select2-selection__choice__remove {
      display: none !important;
    }
    
    .select2-container--focus .select2-autocomplete .select2-selection__choice {
      display: none;
    }
    
    
    
    
    
    

    With an inline search box

    With the search box in the dropdown

    With the selection hidden when it is focused

    By default, Select2 will set up the dropdown to have the search (instead of the selection container) which you will need to override if you want to perfectly emulate a multiple select.

提交回复
热议问题