Select2, when no option matches, “other” should appear

落爺英雄遲暮 提交于 2019-12-22 05:14:27

问题


With select2 dropdown, how do I get a default option to appear if no options match the user's typed input?

$("something").select2({
  formatNoMatches: function(term) {
    //return a search choice
  }
});

I haven't been able to find anything that really matches this desired functionality within the select2 documentation or Stack Overflow.

Edit I'm getting closer with this

$("something").select2({
  formatNoMatches: function(term) {
    return "<div class='select2-result-label'><span class='select2-match'></span>Other</div>"
  }
});

But this is pretty hacky off the bat, and also isn't clickable.


回答1:


To complement on @vararis's answer:

Select2 attached to a <select> element does not allow for custom createSearchChoice nor query functions, hence we will need to manually add an option element (I'll add it as the last option of the element so we can easily .pop it out of the results set):

<select>
  ...
  <option value="0">Other</option>
</select>

Then pass a custom matcher function so that this "Other" option is always matched.

NOTE: Select2 3.4+ uses a different default matcher than the one currently shown in the documentation, this new one has a call to the stripDiacritics function so that a matches á for instance. Therefore I'll apply the default matcher that comes with the Select2 version included in the page to apply its default matching algorithm to any option that's not the "Other" option:

matcher: function(term, text) {
  return text==='Other' || $.fn.select2.defaults.matcher.apply(this, arguments);
},

Finally, we need to remove the "Other" option from the results set when there's any result besides the "Other" result (which is initially always in the results set):

sortResults: function(results) {
  if (results.length > 1) results.pop();
  return results;
}

Demo




回答2:


I solved it by changing the matcher.

$('#activity_log_industry_name').select2
  matcher: (term, text) ->
    if text=="Other"
      return true
    text.toUpperCase().indexOf(term.toUpperCase())>=0

(this is in coffeescript.) The only problem is that "Other" will pop up for any search -- but this can be easily solved by modifying the sortResults function.




回答3:


Try this answer on stackoverflow

createSearchChoice: function (term) {
  return { id: term, text: term };
}



回答4:


Use following code to display the message as 'Other' when no matches found

$("select").select2({ 
formatNoMatches   :    function(term) {       
    return   "Other";
}
});



回答5:


try it, this work in newer version ( Select2 4.0.3 ) without add a new variable.

>>>> Fiddle here <<<<

first you need to download javascript name "github/alasql" to search like query in data

<select id="something">
  ...
  <option value="other">Other</option> <!-- or put this in "dataItemsList" for dynamic option -->
</select>

then in your javascript

// other than this array we will give "other" option
var ajax_search_array = ['your', 'item', 'for', 'search'];

$("#something").select2({
   placeholder: "Choose your something",
   //data: dataItemsList, //your dataItemsList for dynamic option
   //...
   //...
   tags: true,
   createTag: function (tag) {
        // here we add %search% to search like in mysql
        var name_search  = "%"+tag.term.toString().toLowerCase()+"%";

        // alasql search
        var result = alasql('SELECT COLUMN * FROM [?] WHERE [0] LIKE ?',[ajax_search_array, name_search]);

        // if no result found then show "other"
        // and prevent other to appear when type "other"
        if(result==false && tag.term != "other"){
            return {
               id: "other",
               text: "Other"
            };
        }
});

hope this work.




回答6:


In version 4+ of Select2, the matcher should be passed like this:

$("something").select2({
    matcher: function(params, data) {
        if (data.id === "0") { // <-- option value of "Other", always appears in results
            return data;
        } else {
            return $.fn.select2.defaults.defaults.matcher.apply(this, arguments);
        }
    },
});

the "Other" option should be appended to the option list like this:

<select>
  ...
  <option value="0">Other</option>
</select>


来源:https://stackoverflow.com/questions/17950117/select2-when-no-option-matches-other-should-appear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!