Using select2 how can I collapse/expand optgroups? - jquery-select2

I'm using select2 (v 4.0.3) with Bootstrap 3 and I have to display several hundreds of alternatives per optgroup. Now I wish to collapse/expand the optgroups on click to make it a bit more manageable. I couldn't find any info on this so I thought I'd post a question.
I found an approach to this problem but I couldn't get it to work (it seems a bit outdated issue #730). The basic problem with that approach now is that in the current version of select2 elements aren't created until they are needed. Also, the class names seem to have changed a bit, as have apparently the names of events in the move to the latest version.
So far I've managed to get the collapse/expand functionality to work for the optgroups, but issues arise when the user provides text input (check the fiddle).
$(function () {
var data = [
{
text: "Group 1",
children: [
{ id: 'A1', text: 'a1'},
{ id: 'B2', text: 'b2'},
{ id: 'C3', text: 'c3'}]
},
{
text: "Group 2",
children: [
{ id: 'A2', text: 'a2'},
{ id: 'B3', text: 'b3'},
{ id: 'C1', text: 'c1'}
]
}];
$('#mySelect')
.select2({data: data, placeholder : 'Select one' });
// Toggle group on click
$('.select2')
.on('click', function(){
$('.select2-results__option').on('click', function(){
$(this).find('.select2-results__options--nested').toggle();
});
});
});
When the text input is used select2 runs the search and the events I've registered are dropped. My plan was to capture text input and check if the input field is empty or not, based on which I can decide to recreate the optgroup listeners or show all optgroups. Any help in this direction would be appreciated.

Related

Tabulator copyToClipboard method isn't working as anticipated

I am new to the Tabulator plug-in and I am attempting to copy data from one table to another using the Tabulator copyToClipboard method but with no success.
In my application I have created eleven <div> elements (one for the [Crew Leader] and one each for up to ten [Crew Members]) to serve as containers for the Tabulator tables to be instantiated. I am hoping to copy data from the [Crew Leader] table and paste it into each of the affected [Crew Member] tables thus mitigating data re-entry. This sequence of copy/paste events is triggered by the click event bound to a <button> in the header of the [Crew Leader] table. The following function is called by the <button> click event:
function CloneTable() {
// Verify the [Crew Leader] Tabulator table is present....
var tableLeader = Tabulator.prototype.findTable("#CrewLeaderTable");
if (tableLeader.length > 0) {
alert("The Tabulator table #CrewLeaderTable was found.\ntable.length = " + tableLeader.length);
tableLeader.copyToClipboard("all");
alert("The table contents were copied to the clipboard.");
}
else {
alert("The Tabulator table #CrewLeaderTable was not found.");
}
}
The first alert message verifies that the #CrewLeaderTable object has been found as anticipated. However, the second alert verification is never received thus indicating failure of the Tabulator copyToClipboard method.
I have read through as much of the relevant Tabulator documentation as I can find and I am hoping I have simply overlooked something in my setup.
The following is a copy of my Tabulator constructor:
var table = new Tabulator(divid, {
height: "100%",
layout: "fitDataFill",
movableRows: true, //enable user movable rows
tabEndNewRow: true, //create empty new row on tab
rowContextMenu: myActionContextMenu,
keybindings: {
"navUp": true, //enable navUp keybinding using the "up arrow" key
"navDown": true, //enable navDown keybinding using the "down arrow" key
},
columns: [
{ title: "Phase Code", field: "phaseCode", width: 144, editor: "select", editorParams: { values: function (cell) { return window.laborPhaseCodes; } } },
{ title: "Date Worked", field: "dateComp", hozAlign: "center", sorter: "date", editor: dateEditor },
{ title: "Start Time", field: "timeStart", hozAlign: "center", sorter: "time", editor: timeEditor },
{ title: "Finish Time", field: "timeFinish", hozAlign: "center", sorter: "time", editor: timeEditor },
{ title: "Memo", field: "memo", width: 144, hozAlign: "left", editor: "input" },
{ title: "<button type='button' id='btnClone' class='btn btn-success btn-sm py-0' style='font-size:10px;'>Clone</button>", headerSort: false, headerClick: tabCloneTable }
],
cellEdited: function (cell) {
}
});
I have spent a couple of days trying to figure out the best way to "clone" the data from one table into another. The Tabulator documentation is fairly comprehensive but I fear I have overlooked something. Any assistance is greatly appreciated.
It looks like copyToClipboard doesn't return the data, it is maintained internally and not accessible. But, with what you are doing set/getData works fine.
Here is an example, https://jsfiddle.net/nrayburn/19sjg74k/7/.
Basically, what you want to do is call getData on the parent table and setData on the child table.
const crewLeaderTable = Tabulator.prototype.findTable('#CrewLeaderTable')[0];
const crewMemberTable = Tabulator.prototype.findTable('#CrewMember1Table')[0];
const crewLeaderData = crewLeaderTable.getData();
// You could also use replaceData or addData, depending on the requirements
crewMemberTable.setData(crewLeaderData);

Get reference from ext component

I'm having difficulties retrieving my input values through Extjs6's references. There doesn't seem to be a clear cut answer and google is polluted with answers that seem distinct to many different Extjs versions.
I have a window which contains a textfield and a save button, from the textfield I need to retrieve the user's input and pass it along to my ajax call.
My code:
window.updatePassword = function(button) {
var win = new Ext.Window({
referenceHolder: true,
items: [{
xtype: 'form',
items: [{
xtype: 'textfield',
fieldLabel: "newPassword",
reference: 'newPassword',
inputType: 'password'
}],
}],
buttons: [{
text: 'save',
handler: function (btn) {
Ext.Ajax.request({
url: '../../Password_updatePassword.action',
params : {
newPassword: win.newPassword
},
scope: this,
disableCaching: true
});
},
scope: this
}]
});
win.show(this);
};
The things I've tried so far:
this.lookupReference('newPassword')
win.values
win.getValues()
win.newPassword
Ext.getCmp('newPassword')
Any advice would be appreciated.
this.lookupReference('newPassword') - This refers to current object
and handler dont have any component to lookup.
win.values - doesnt make any sense unless you have created a config
in win.
win.getValues() - again doesnt make any sense unless you have create a method in win.
win.newPassword - again same.
Ext.getCmp('newPassword') - getCmp works with id, not with reference.
To get the reference of password field you can lookup on win object,
win.lookupReference('newPassword');
To get the value you have to use getValue() method.
win.lookupReference('newPassword').getValue();

Select2 Multiple: Add several items with one copy+paste

I want to add several items in a select2 input field at once.
If I copy+paste "Hawaii Alaska" into the select-multiple example here, then I get:
No results found
In my case spaces are not allowed in the items.
Is there a way to insert N space sperated items via copy+paste?
Desired result: (x)Hawaii (x)Alaska
you can add token separators in your select2 to identify characters as stopping points for your tags/choices, but unfortunately it bugs on the last copy pasted item
//try copy pasting bug,invalid, enhancement, wontfix
//then try bug,invalid, enhancement
//you will see the problem
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
var placeholder = "select";
$(".mySelect").select2({
tokenSeparators: [',', ', ', ' '],
data: data,
placeholder: placeholder,
allowClear: false,
minimumResultsForSearch: 5
});
here is the codepen
http://codepen.io/anon/pen/dMWQbd
its opened as a bug in github on the library
https://github.com/select2/select2/issues/3458

Select2 Find existing or type new always show first option as blank

I added a select2 and it always show first option as blank.
just below the blank option, it always shows what i type in select2 textfield. Any Idea, how i can fix it.
= hidden_field_tag :tags // present in HAML form
// javascript
$('#tags').select2
createSearchChoice: (term, data) ->
if $(data).filter((->
#text.localeCompare(term) == 0
)).length == 0
return {
id: term
text: term
}
return
multiple: false
data: [
{
id: 0
text: 'story'
}
{
id: 1
text: 'bug'
}
{
id: 2
text: 'task'
}`enter code here`
]
Try this .....
Your input field should be like this
%input#tags{:style => "width: 300px", :type => "hidden"}
Your js code should be like this
$("#tags").select2({
placeholder:"Select an option",
createSearchChoice: function(term, data) {
if ($(data).filter((function() {
return this.text.localeCompare(term) === 0;
})).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: false,
data: [
{
id: 0,
text: 'story'
}, {
id: 1,
text: 'bug'
}, {
id: 2,
text: 'task'
}
]
});
You no longer need to use createSearchChoice if you want to do this with Select2, you can just use the tags option. Right now you shouldn't be seeing the blank option, as you aren't passing one to Select2 at all, so this is lacking a bit of information that would explain that issue.
Select2 will automatically hide blank options though if you have a placeholder set, which I would always recommend. So the hacky solution is to set the placeholder option to whatever you want ("Select a few tags..."), but that only works if this is actually a blank option and not just a CSS issue. You can tell if it's a blank option if Select2 highlights it whenever you start searching, as it will automatically highlight the first option.
It would make more sense for this to be a CSS issue, maybe a bit too much padding somewhere, as the tag (or choice from createSearchChoice) should be inserted automatically at the top of the search results. So even if there was a spare blank option sitting around, it would show under the newly created search choice.

jQuery Select2 - Highlighting the child (when the search term matches) instead of its parent in hierarchical list

Select2 3.5.2.
I have some hierarchical data in a select2 list where the parents AND children are all valid selections. If possible, when the search term matches a child, I'd like the child to be highlighted by default instead of the parent.
For example, given the following code...
$("#hdn").select2(
{
width: '300px',
data:
[
{
id: 1,
text: 'Italy',
children:
[
{ id: 2, text: 'Italy - Sardinia' },
{ id: 3, text: 'Italy - Sicily' },
]
},
{
id: 4,
text: 'United Kingdom',
children:
[
{ id: 5, text: 'United Kingdom - Guernsey' },
{ id: 6, text: 'United Kingdom - Jersey' }
]
}
]
});
... if you start typing 'Jer', it currently highlights 'United Kingdom' by default:
Ideally, if you start typing 'Jer', it should highlight 'United Kingdom - Jersey' by default instead.
Because this is a group I still want the parent to show as an option, I just want the child to be highlighted by default instead.
See this fiddle: http://jsfiddle.net/moo_ski_doo/atnph13b/2/
Select2 will highlight the first option which is selectable by default. If you don't want the highlight to sit on "United Kingdom" first, you are going to have to remove the id.
Select2 3.5.2 does not provide an easy way to change how what option is highlighted by default.

Resources