[javascript] "query function not defined for Select2 undefined error"

Trying to use Select2 and getting this error on multiple item input/text field:

"query function not defined for Select2 undefined error"

This question is related to javascript runtime-error jquery-select2

The answer is


I also had this problem make sure that you don't initialize the select2 twice.


This issue boiled down to how I was building my select2 select box. In one javascript file I had...

$(function(){
  $(".select2").select2();
});

And in another js file an override...

$(function(){
    var employerStateSelector = 
                $("#registration_employer_state").select2("destroy");
    employerStateSelector.select2({
    placeholder: 'Select a State...'
    });
});

Moving the second override into a window load event resolved the issue.

$( window ).load(function() {
  var employerStateSelector = 
              $("#registration_employer_state").select2("destroy");
  employerStateSelector.select2({
    placeholder: 'Select a State...'
  });
});

This issue blossomed inside a Rails application


I got the same error. I have been using select2-3.5.2

This was my code which had error

    $('#carstatus-select').select2().val([1,2])

Below code fixed the issue.

    $('#carstatus-select').val([1,2]);

I have a complicated Web App and I couldn't figure out exactly why this error was being thrown. It was causing the JavaScript to abort when thrown.

In select2.js I changed:

        if (typeof(opts.query) !== "function") {
            throw "query function not defined for Select2 " + opts.element.attr("id");
        }

to:

        if (typeof(opts.query) !== "function") {
            console.error("query function not defined for Select2 " + opts.element.attr("id"));
        }

Now everything seems to work properly but it is still logging in error in case I want to try and figure out what exactly in my code is causing the error. But for now this is a good enough fix for me.


In case you initialize an empty input do this:

$(".yourelement").select2({
 data: {
  id: "",
  text: ""
 }
});

Read the first comment below, it explains why and when you should use the code in my answer.


if (typeof(opts.query) !== "function") {
    throw "query function not defined for Select2 " + opts.element.attr("id");
}

This is thrown becase query does not exist in options. Internally there is a check maintained which requires either of the following for parameters

  • ajax
  • tags
  • data
  • query

So you just need to provide one of these 4 options to select2 and it should work as expected.


It seems that your selector returns an undefined element (Therefore undefined error is returned)

In case the element really exists, you are calling select2 on an input element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}]).


use :

try {
    $("#input-select2").select2();
}
catch(err) {

}

For me this issue boiled down to setting the correct data-ui-select2 attribute:

<input type="text" data-ui-select2="select2Options.projectManagers" placeholder="Project Manager" ng-model="selectedProjectManager">


$scope.projectManagers = { 
  data: []  //Must have data property 
}

$scope.selectedProjectManager = {};

If I take off the data property on $scope.projectManagers I get this error.


This error message is too general. One of its other possible sources is that you're trying to call select2() method on already "select2ed" input.


I also got the same error when using ajax with a textbox then i solve it by remove class select2 of textbox and setup select2 by id like:

$(function(){
  $("#input-select2").select2();
});

Also got the same error when using ajax.

If you're using ajax to render forms with select2, the input_html class must be different from those NOT rendered using ajax. Not quite sure why it works this way though.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to runtime-error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined' what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? javac: invalid target release: 1.8 C++ error : terminate called after throwing an instance of 'std::bad_alloc' Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error No Main class found in NetBeans Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0 TypeError: Cannot read property "0" from undefined Array Index Out of Bounds Exception (Java) Excel VBA Automation Error: The object invoked has disconnected from its clients

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?