最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select2, when no option matches, "other" should appear - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Jul 30, 2013 at 14:58 varatis asked Jul 30, 2013 at 14:41 varatisvaratis 14.7k24 gold badges75 silver badges115 bronze badges 7
  • 1 Not too familiar with select2, but this posting might help: github.com/ivaynberg/select2/issues/448 – tymeJV Commented Jul 30, 2013 at 14:43
  • Are you using it attached to a select or hidden input? – Fabrício Matté Commented Jul 30, 2013 at 14:45
  • Reading last documentation (I used an old version) I see there's a way to do it with a function, but indicating the action after an underscore, it could be $("something_get") for example. I only had to use basic matching. – Max Rios Commented Jul 30, 2013 at 14:52
  • @MaximilianoRios Can you elaborate, or point me to the documentation you're viewing? – varatis Commented Jul 30, 2013 at 14:54
  • Of course, find it here: ivaynberg.github.io/select2 – Max Rios Commented Jul 31, 2013 at 14:14
 |  Show 2 more comments

7 Answers 7

Reset to default 9

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

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.

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>

To customize formatNoMatches use following code in your view

ui-select2="{formatNoMatches:'No Results Found'}"

Try this answer on stackoverflow

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

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

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

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.

发布评论

评论列表(0)

  1. 暂无评论