Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Select2's createSearchChoice function

Tags:

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.

like image 446
jrrdnx Avatar asked Jul 26 '12 17:07

jrrdnx


2 Answers

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.

like image 57
Jürgen Paul Avatar answered Sep 22 '22 12:09

Jürgen Paul


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

like image 39
Jeff Dickey Avatar answered Sep 20 '22 12:09

Jeff Dickey