Using SELECT2 4.0.0 with infinite Data and filter

后端 未结 2 1186
误落风尘
误落风尘 2021-02-04 13:33

I\'m using Select2 now since 2 years and I really enjoy all dev made. however, version 3.5.x has his limit, so I\'m moving to version 4.0, which give me headaches!

For y

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 14:02

    I'd highly recommend reading the release notes and the 4.0 release announcement when migrating from Select2 3.5.2 to Select2 4.0.0.

    With version 3.5.2, I can reproduce the underline match when searching for data (using formatSelection and query.term).. any idea how to make it with v4.0.0 (function templateResult only pass 'result' and not 'query' anymore ?

    This was removed in 4.0 because the results have been separated from the queries, so it didn't make sense to keep passing along the information. Of course, this doesn't mean you can't get the query and store it. All you would need to do is store the query, something like the following might work

    var query = {};
    var $element = $('#my-happy-select');
    
    function markMatch (text, term) {
      // Find where the match is
      var match = text.toUpperCase().indexOf(term.toUpperCase());
    
      var $result = $('');
    
      // If there is no match, move on
      if (match < 0) {
        return $result.text(text);
      }
    
      // Put in whatever text is before the match
      $result.text(text.substring(0, match));
    
      // Mark the match
      var $match = $('');
      $match.text(text.substring(match, match + term.length));
    
      // Append the matching text
      $result.append($match);
    
      // Put in whatever is after the match
      $result.append(text.substring(match + term.length));
    
      return $result;
    }
    
    $element.select2({
      templateResult: function (item) {
        // No need to template the searching text
        if (item.loading) {
          return item.text;
        }
    
        var term = query.term || '';
        var $result = markMatch(item.text, term);
    
        return $result;
      },
      language: {
        searching: function (params) {
          // Intercept the query as it is happening
          query = params;
    
          // Change this to be appropriate for your application
          return 'Searching…';
        }
      }
    });
    

    With version 3.x, you can add free entries using search value was not in the list (using createSearchChoice). V4.0 has not this option, any idea how to make it again ?

    This can still be done in 4.0 using the tags option (set it to true). If you want to customize the tag, you can use createTag (similar to createSearchChoice).

    var $element = $('#my-happy-select');
    
    $element.select2({
      createTag: function (query) {
        return {
          id: query.term,
          text: query.term,
          tag: true
        }
      },
      tags: true
    });
    

提交回复
热议问题