"query function not defined for Select2 undefined error" - javascript

Trying to use Select2 and getting this error on multiple item input/text field:
"query function not defined for Select2 undefined error"

Covered in this google group thread
The problem was because of the extra div that was being added by the select2. Select2 had added new div with class "select2-container form-select" to wrap the select created. So the next time i loaded the function, the error was being thrown as select2 was being attached to the div element. I changed my selector...
Prefix select2 css identifier with specific tag name "select":
$('select.form-select').select2();

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.

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.

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

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 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 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();
});

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"}]).

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.

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.

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.

Related

JQuery validate custom error message is not showing up

Following is the form validation javascript in my application:
$('#EmploymentHistoryForm').validate({
ignore: ':hidden, [readonly=readonly]',
rules: {
'MemberJob.Phone': {
PhoneFieldValidation: true
}
},
messages: {
'MemberJob.Phone': {
PhoneFieldValidation: $.viewUrl.url.invaliedPhoneMessage
}
},
showErrors: function (errorMap, errorList) {
ShowErrors(errorMap, errorList, this.validElements());
},
submitHandler: function (form, event) {
event.preventDefault();
return false;
}
});
Here, $.viewUrl.url.invaliedPhoneMessage is set at the cshtml page (in ASP.NET MVC), and while debugging the javascript I can see proper value in that variable when $('...').validate function gets hit.
I have registered a new validator "PhoneFieldValidation" in JQuery validators collection:
$.validator.addMethod("PhoneFieldValidation", ValidatePhoneAndAltPhone);
Following is the rendered HTML for the input control for which I have added this validation rule:
<input class="PhoneFieldValidation" id="MemberJob_Phone" name="MemberJob.Phone" type="text" required="required" aria-required="true">
I can see the validation getting fired correctly. That means, "ValidatePhoneAndAltPhone" method is getting called, and returning a boolean result based on the input.
However, the error message is not getting displayed properly. It displays "Warning: No message defined for MemberJob.Phone" instead of "Invalid Phone Number".
While debugging through customMessage function of jquery.validate.js, I could see "this.settings.messages" collection is not having the message for "MemberJob.Phone" field, and that looks to be the root cause of this issue.
Any idea of how to resolve this issue?
I know we can add "data-msg-[rulename]" attribute in the HTML tag which will fix the issue. But I am sure the current approach I am following is also correct. Seems I am missing something.
Any help on this will be much appreciated.
Thanks
You never mentioned where $.viewUrl.url.invaliedPhoneMessage comes from.
If there is already a message defined in your custom PhoneFieldValidation method, then you would not define a message within the messages object.
Otherwise, you cannot use a JavaScript variable within the messages object without a function.
The whole problem is being caused by the Unobtrusive plugin which is automatically constructing the .validate() method call. You cannot call .validate() more than once on the same form; and all subsequent calls are ignored. Instead, you can simply define the custom message for PhoneFieldValidation within its .addMethod() method.
$.validator.addMethod("PhoneFieldValidation", function(value, element) {
// your custom method function here;
}, "This is your custom validation error message");

Displaying success/failure message on the form using dojo

I am creating a application using dojo 1.8.
I have a form with buttons to perform some action. Once the action is done, I get the status of the backend process execution. Currently I am using alert boxes to intimate user about the status. I know, it is very old fashioned. So what I am trying is: If the status is "success" then I will display a message (in green text) on the top of the form else the error message (in red).
For that in HTML file, I created two DIVs
<div id="successNotification" data-dojo-attach-point="successNotification"></div>
<div id="failureNotification" data-dojo-attach-point="failureNotification"></div>
and in the postCreate method, in requestCompleteCallback method of request.invokePluginService, I am trying to set the innerHTML of the DIV tag.
But below code always results in "successNotification is undefined" error.
if (ifSuccess == 'true' || ifSuccess )
{
var successNotification = dijit.byId("successNotification");
}
In the same block I have used dijit.byId("some other component") and that works fine.
what am I doing wrong?
I'm noticing several things here. First of all, your if code does not look valid (there's a ' after true).
Then, if you're creating custom widgets you should not retrieve widgets or DOM nodes by their ID, which means you should not use either:
dijit.byId()
dojo.byId()
dojo/dom::byId()
dijit/registry::byId()
The correct way is by using the attach points you created by using the data-dojo-attach-point attribute. When you inherit from the dijit/_TemplateMixin mixin, you can simply use: this.successNotification and if you inherit from dijit/_WidgetsInTemplateMixin as well, then you can use the same syntax to retrieve widget instances.
In your case it would be:
if (ifSuccess) {
var successNotification = this.successNotification;
}

twitter typeahead.js + bootstrap tagsinput = Object [object Object] has no method 'setQuery'

I'm using Twitter typeahead with Bootstrap Tags Input. The code looks like this:
$(selector).tagsinput('input').typeahead({
name:'tags',
remote: "/admin/tags/search/%QUERY?format=json"
}).bind('typeahead:selected', function (object, datum) {
$(selector).tagsinput('add', datum);
$(selector).tagsinput('input').typeahead('setQuery', 'test');
});
This is pretty much copied from the example here: http://timschlechter.github.io/bootstrap-tagsinput/examples/bootstrap3/
(to see the original example you need to click 'Show code' in the Typeahead section.
It works apart from the line $(selector).tagsinput('input').typeahead('setQuery', ''); which gives me this error:
Uncaught TypeError: Object [object Object] has no method 'setQuery'
That line is supposed to reset the text that has already been entered to typeahead control after the suggestion has been added to the list of tags. If I add the same line outside of the even callback like this:
$(selector).tagsinput('input').typeahead('setQuery', 'test');
It works.
The only thing I noticed buy debugging is that $(selector).tagsinput('input').typeahead points to a different function outside and inside the event handler function.
Any ideas?
i write this
$("#TagsInput").tagsinput("input").typeahead("val", "");
I had same problem. There you can see the correct use.
You must set typeahead in second line:
$(selector).tagsinput();
$(selector).tagsinput('input').typeahead('setQuery', '');

javascript error: Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

I am getting this error when I call a javascript function to display a modal window:
Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object
The code block is:
else if (action=="officeview") {
document.getElementById("OfficeContent").src="ChangeView.aspx";
ShowFeatureModal('AppView','OfficeContent')
The object is this situation, does exist.
Error is caused at: document.getElementById line.
What else could be causing the error?
Update:
Index.aspx is calling the javascript function which is located in sysUtilities.js file. The source file is yet a seperate page (ChangeView.aspx)
If document.getElementById doesn't find the element, it will return null. If you then try to get the src property from null, you'll get this error.
You'll either need to ensure the there's an element with its ID equal to OfficeContent or do something like the following:
else if (action=="officeview") {
var officeContent = document.getElementById("OfficeContent")
if (officeContent) {
officeContent.src="ChangeView.aspx";
ShowFeatureModal('AppView','OfficeContent')
}
}
EDIT: If you're using ASP.NET, which it appears that you are, remember that your IDs might be getting name-mangled if they are inside a container control. In that case, you have to make sure to use the ClientID, not the plain old ID. Something like this:
document.getElementById("<%= OfficeContent.ClientID %>")
Don't know if it will help in this case, but this is a trick to prevent the error:
(document.getElementById("OfficeContent")||{}).src="ChangeView.aspx";
If the element doesn't exist, an empty object gets the src-property, no error is thrown, no harm is done.
It may be wise though to look for the cause of document.getElementById("OfficeContent") returning null.
you need test whether an element exists first before setting element's src attribute
var el = document.getElementById("OfficeContent");
el && (el.src="ChangeView.aspx");
All this stuff is peripheral to the main issue, which is:
You must use the actual clientID of "OfficeContent", which may be quite different in the HTML DOM of the page as it is rendered. One easy way to avoid this would look something like this:
var officeContent = document.getElementById("<%=OfficeContent.ClientID %>")

jQuery missing : after property id

$('#note').click({
$('#trigger').remove();
$('#info').slideDown(4000, function(){
$(this).fadeOut(40000);
});
});
What I'm trying to do here is obvious. Sadly, when I try this piece of code, FireBug throws the following error: missing : after property id.
After trying to debug for some time, I saw that seemingly nothing is wrong. The highlighting shows correctly in my editor (Notepad++), and no previous error was found.
Thank you in advance for any help.
click expects a function. You are trying to pass it a pseudo object-literal having an invalid syntax.
$('#note').click(function() { // pass a function to "click"
$('#trigger').remove();
$('#info').slideDown(4000, function(){
$(this).fadeOut(40000);
});
});

Categories