Display result matching optgroup using select2 - jquery-select2

I'm using select2 with Bootstrap 3.
Now I would like to know whether it is possible to display all optgroup items if the search matches the optgroup name while still being able to search for items as well. If this is possible, how can I do it?

The above answers don't seem to work out of the box with Select2 4.0 so if you're hunting for that, check this out: https://github.com/select2/select2/issues/3034
(Use the function like this: $("#example").select2({matcher: modelMatcher});)
function modelMatcher (params, data) {
data.parentText = data.parentText || "";
// Always return the object if there is nothing to compare
if ($.trim(params.term) === '') {
return data;
}
// Do a recursive check for options with children
if (data.children && data.children.length > 0) {
// Clone the data object if there are children
// This is required as we modify the object to remove any non-matches
var match = $.extend(true, {}, data);
// Check each child of the option
for (var c = data.children.length - 1; c >= 0; c--) {
var child = data.children[c];
child.parentText += data.parentText + " " + data.text;
var matches = modelMatcher(params, child);
// If there wasn't a match, remove the object in the array
if (matches == null) {
match.children.splice(c, 1);
}
}
// If any children matched, return the new object
if (match.children.length > 0) {
return match;
}
// If there were no matching children, check just the plain object
return modelMatcher(params, match);
}
// If the typed-in term matches the text of this term, or the text from any
// parent term, then it's a match.
var original = (data.parentText + ' ' + data.text).toUpperCase();
var term = params.term.toUpperCase();
// Check if the text contains the term
if (original.indexOf(term) > -1) {
return data;
}
// If it doesn't contain the term, don't return anything
return null;
}

Actually found the solution by modifying the matcher opt
$("#myselect").select2({
matcher: function(term, text, opt){
return text.toUpperCase().indexOf(term.toUpperCase())>=0 || opt.parent("optgroup").attr("label").toUpperCase().indexOf(term.toUpperCase())>=0
}
});
Under the premise that the label attribute has been set in each optgroup.

Found a solution from select2/issues/3034
Tested with select2 v.4
$("select").select2({
matcher(params, data) {
const originalMatcher = $.fn.select2.defaults.defaults.matcher;
const result = originalMatcher(params, data);
if (
result &&
data.children &&
result.children &&
data.children.length
) {
if (
data.children.length !== result.children.length &&
data.text.toLowerCase().includes(params.term.toLowerCase())
) {
result.children = data.children;
}
return result;
}
return null;
},
});

A few minor changes to people suggested code, less repetitive and copes when there are no parent optgroups:
$('select').select2({
matcher: function(term, text, opt){
var matcher = opt.parent('select').select2.defaults.matcher;
return matcher(term, text) || (opt.parent('optgroup').length && matcher(term, opt.parent('optgroup').attr("label")));
}
});

Related

Google Sheets Script Error - Cannot read property '1' of null (line 7)

I'm using the following script to pull data from bulk json files:
function importRegex(url, regexInput) {
var output = '';
var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
if (fetchedUrl) {
var html = fetchedUrl.getContentText();
if (html.length && regexInput.length) {
output = html.match(new RegExp(regexInput, 'i'))[1];
}
}
// Grace period to not overload
Utilities.sleep(1000);
return output;
}
Then this formula with the desired URL in E3:
=IMPORTREGEX(E3,"(.*')")
It worked completely fine to begin with, now I'm suddenly getting the error, seemingly without making any changes, any tips?
This error is because of lacking a null check.
You are now using the return value of html.match() whether it is null or not.
So you should check if the return value is null and if it has enough length.
Like this:
if (html.length && regexInput.length) {
let match = html.match(new RegExp(regexInput, 'i'));
if ( match != null && match.length > 1 ){
output = match[1];
}
}

selec2 search - Return no results found message if a specific criteria didnt match

I am using select2 4.0.3 for search drop down. As per my understanding its default functionality is not to match with the start of entries the drop down have. So I have implemented the below given code
function matchStart(params, data) {
params.term = params.term || '';
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
return data;
}
return false;
}
$("select").select2({
placeholder : "Input country name or select region",
matcher : function (params, data) {
return matchStart(params, data);
},
});
My problem is, the dropdown is not showing "No results found" message even if there is no matching results found. Can anyone help me on this.
Thanks in advance.
Try changing the return value of matchStart from false to null.
Also you can remove the extra function around the matcher argument. The result:
function matchStart(params, data) {
params.term = params.term || '';
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
return data;
}
return null;
}
$("select").select2({
placeholder: "Input country name or select region",
matcher: matchStart
});

Select no longer highlighting text on iPad (word)

In my add-in we navigate the document by calling select on either a paragraph or a search result from inside a paragraph. In the newest version of Word for iOS : 2.0.2 (170415) the document is scrolling to the correct part of the document but the text is no longer highlighting. This was working in the previous released version of word.
Oddly the text does highlight as expected if i open the search bar, and then navigate around my document.
public SelectTextInstance(text: string, paragraphIndex: number, textInstance: number) {
Word.run(function (context) {
// Create a proxy object for the paragraphs collection.
var paragraphs = context.document.body.paragraphs;
context.load(paragraphs, 'text,font');
return context.sync().then(function () {
if (paragraphIndex == -1) {//currently would occur for items that are inside of tables.
return;
}
var paragraph = paragraphs.items[paragraphIndex];
return context.sync().then(function () {
var ranges = null;
//256 is the maximum length for a search item. Longer than this and we just have to select the paragraph.
if (text != undefined && text != null && text.length <= 256) {
ranges = paragraph.search(text, { matchCase: true, ignoreSpace: true});
context.load(ranges, 'text');
}
return context.sync().then(function () {
if (ranges == null || ranges.items.length == 0) {
paragraph.select();
}
else {
//select the paragraph rather than overflow - something bad happened somewhere, so we'll fall back to highlighting the paragraph.
if (ranges.items.length <= textInstance) {
paragraph.select();
} else {
ranges.items[textInstance].select();
}
}
return context.sync().then(function () {
});
});
});
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
}
Thanks so much for reporting this. Effectively this is a regression. The range is selected but not colored. We will push the fix for the next update.

my checkbox pass value even unchecked - Grails

I have lots of checkbox element on my Grails form, one is this:
<g:checkBox id="consolidate" name="consolidate" value="${true}" checked="${false}" />
Then on the receiving controller, I verify the value of the checkbox using this code:
println params?.consolidate
And it displays:
on
Regardless whether I've tick my checkbox or not. In other language, if the checkbox is not ticked, its value on the controller will be null or undefined. What should be its value when unchecked, and what is the right code to access its value on the grails controller?
Temporary Solution:
The following code (on JavaScript) is what I had used temporarily to accommodate my requirement. Though what I want is an explanation or maybe correction about this behavior.
var serialized_string = "";
$("#form input").each(function(i, j) {
var o = $(j);
if(o.val() !== undefined && o.val() !== "undefined" && o.val() !== "") {
if(serialized_string === "") {
serialized_string += o.attr("name") + "=";
}
else {
if(o.attr("name") === "consolidate") {
var val = "false";
if(o.prop("checked")) {
val = "true";
}
data += val;
}
else {
data += "&" + o.attr("name") + "=";
}
}
}
});
If checked, you see the on you're seeing; otherwise you see null, which is your false.

Why am I getting this error in a basic Rails+Ember app?

I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)

Resources