Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - Custom match jquery select2

I have this sample jquery select2:

$('#example').select2({
  escapeMarkup: function (markup) {
    return markup;
  },
/*   templateResult: formatResult,
  templateSelection: formatResult, */
  tags: true,
  createTag: function (params) {
    // Don't offset to create a tag if there is no @ symbol
    if (params.term.match(/[a-z]/i)) {
      // Return null to disable tag creation
      return {
        id: params.term,
        text: params.term +' <span class="new-category-text">Click to add as new category</span>',
        tag: true
      }
    }
    return null;
  },
  matcher: matchCustom,
  sorter: function(results) {
    for (var x in results) results[x].text.includes('Click to add as new category') ? results.push(results.splice(x, 1)[0]) : 0;
    return results;
  },
});

function formatResult(state)
{

  if (state.text === '-- Select --') {
    return '<span class="text-danger">'+state.text+'</span>';
  }
  if (!state.id || !state.element) {
    // console.log(state);
    return state.text;
  }

  if(state.element.dataset.global === '1'){
    return '<span>'+state.text+'</span><span class="float-right">Standard</span>';
  }else{
    return '<span>'+state.text+'</span>';
  }
}

function matchCustom(params, data) {
    // console.log("params",params);
    // console.log("data",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.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        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;
    }else{
        let splittedText = splitTermText(data.text);
        splittedText.forEach(function(v,i){
        console.log(v);
        //checking if any of splitted value starts from searched term
        //ignoring first words because it must be started from other
        //words else it would have returned from above 
            if(i != 0){
              if (v.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
                var modifiedData = $.extend({}, data, true);
                return modifiedData;
              }
            }
        });
    }

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

function splitTermText(term)
{
var separators = [' ', '-', '\(', '\)', '/', ':'];
let splitted = term.split(new RegExp(separators.join('|'), 'g'));
return splitted.filter(v => v !== "")
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="example" multiple="multiple" style="width: 300px">
    <option value="Apple">Apple</option>
    <option value="Bat">Bat</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
    <option value="Elephant">Elephant</option>
    <option value="View/Exposure">View/Exposure</option>
    <option value="View / Exposure">View / Exposure</option>
    <option value="Dummy - Data">Dummy - Data</option>
    <option value="Dummy-Data">Dummy-Data</option>
</select>
question from:https://stackoverflow.com/questions/66060262/custom-match-jquery-select2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have just simplified your program and it seems ok with what you want. I am using RegExp and match

$('#example').select2({
  escapeMarkup: function (markup) {
    return markup;
  },
/*   templateResult: formatResult,
  templateSelection: formatResult, */
  tags: true,
  createTag: function (params) {
    // Don't offset to create a tag if there is no @ symbol
    if (params.term.match(/[a-z]/i)) {
      // Return null to disable tag creation
      return {
        id: params.term,
        text: params.term +' <span class="new-category-text">Click to add as new category</span>',
        tag: true
      }
    }
    return null;
  },
  matcher: matchCustom,
  sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
});


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
    var sregex = `(^${params.term}|[ :\-\/\(\)]${params.term})`;

    //var regex = new RegExp(sregex);// case sensitive
    var regex = new RegExp(sregex, 'i'); // nocase
    if(data.text.match(regex)){
       var modifiedData = $.extend({}, data, true);
      return modifiedData;    
    }

    // Return `null` if the term should not be displayed
    return null;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="example" multiple="multiple" style="width: 300px">
    <option value="Apple">Apple</option>
    <option value="Bat">Bat</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
    <option value="View/Exposure">View/Exposure</option>
    <option value="Elephant">Elephant</option>
    <option value="View / Exposure">View / Exposure</option>
    <option value="Dummy - Data">Dummy - Data</option>
    <option value="Dummy-Data">Dummy-Data</option>
    <option value="Dummy:Data">Dummy:Data</option>
    <option value="Dummy(Data)">Dummy(Data)</option>    
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...