Using Select2's createSearchChoice function
Asked Answered
H

2

22

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.

Hermeneutics answered 26/7, 2012 at 17:21 Comment(2)
Could you post your html and javascript code that hooks it up?Malan
Looks like you need to use hidden - but you can set the "options" in the data hookup data: ...Malan
M
28

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.

Mcauliffe answered 29/7, 2012 at 7:40 Comment(5)
Aw, I was so hoping for some bounty! Glad you figured it out though.Malan
It turns out the query parameter isn't required, but the data parameter is required to be in the same constructor. The form input was being added to my page with a class specific to the framework I'm using and included one constructor with the data parameter, and I was trying to add createSearchChoice in a separate constructor unique to the page. A little bit of customization and everything is working now. Sorry for the delayed response. Your answer got me going in the right direction though, so please keep your bounty. :)Hermeneutics
@Hermeneutics Can you please post part of your code regarding the query and data parameters?Collection
by using input, it messes up the Jquery validation. it does not scroll to the right element. can you help me out?Medin
Can you provide the complete code in a jsfiddle? Where does the hidden input go - right before your select?Loveland
P
2

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

Pilothouse answered 5/4, 2013 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.