Using Select2's createSearchChoice function

坚强是说给别人听的谎言 提交于 2019-11-29 05:39:30

问题


I'm trying to use the createSearchChoice function to allow users to enter their own choice when the default list won't suffice. When I try to use this function on a <select> element, I get the following error:

Error: Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.

I tried using an <input type='hidden'> element instead, but now get the following error:

Error: uncaught exception: query function not defined for Select2 'MyInputName'

I'd prefer to use the select element to stay in line with existing code (need the ability to select multiple options), but just need the ability for users to input their own option in addition to selecting from a prior list.


回答1:


Oh God, How do I cancel this bounty. I panicked and due to panicking I was able to answer what we were both looking for:

You can't use createSearchChoice on a select. So you have to use an input instead.

<input type="hidden" id="category">

The fix is to use the query parameter:

$("#category").select2({query:function(query){
  var data = {results: []};
  data.results.push({text: query.term});
  query.callback(data);
}});

What this does is add the current term to the options if it's not there. You can populate the results object like so:

var data = {results: [{text:'math'},{text:'science'}]};

This solved my problem so I hope it solved yours. I think we should read more on the documentation.




回答2:


I had this problem and it was due to calling select2 on the same field twice



来源:https://stackoverflow.com/questions/11674647/using-select2s-createsearchchoice-function

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