Hide selected items in select2 - jquery-select2

I'm trying to use select2 jQuery plugin to enhance a select element in HTML app. The select allow to choose multiple items.
I'll like to remove the items that are currently selected from the dropdown. I didn't find explicit solution in the docs.
The current solution I've found was to use templateResult option and have the template function return null if the item is selected. This cause Results.prototype.template function to set container.style.display = 'none' but this has the side-effect of causing the keyboard to still select those items even though they are not visible.

Just apply this CSS.
.select2-results__option[aria-selected=true] { display: none;}
Small Update for recent versions :
.select2-results__option--selected { display: none;}
Source

Check out the answer provided here, provided by Hakam Fostok.
I've reproduced his answer below here for completeness:
my solution was modified the select2.js (the core, version 4.0.3) in the line #3158. Add the following verification :
if ($option[0].selected == true) {
return;
}
With this verification, we can exclude from the dropdown list, the selected ones. And if you write the name of a selected option, appear the text of option "noResult" .
Here the complete code:
SelectAdapter.prototype.query = function (params, callback) {
var data = [];
var self = this;`
var $options = this.$element.children();`
$options.each(function () {
var $option = $(this);
if (!$option.is('option') && !$option.is('optgroup') ) {
return;
}
if ($option[0].selected == true) {
return;
}
var option = self.item($option);
var matches = self.matches(params, option);
if (matches !== null) {
data.push(matches);
}
});
callback({
results: data
});
};
For my purposes, I was using the select2.js file, so I made the change at line 3195.

For versions 4 and 4.1
.select2-container--default .select2-results__option[aria-selected=true] {
display: none !important;
}
Works fine!

In addition to #Satheez answer, this script will let you maintain the placeholder after hiding all the selected items.
$('.selector').select2().on("change", function (e) {
$('.select2-search__field').attr('placeholder', 'Here is your placeholder');
});

Related

Select2 - Show/Hide div based on selection

I am trying to have a div show if an option is selected using the Select2 plug in.
I tried using the following code but it does not work:
$(document).ready(function() {
var h = $(".shipment-details--other-description");
$("#shipment-details-select-pacakage-types").change(function() {
if (this.checked && this.value == "Other") {
h.show();
} else {
h.hide();
}
}).change()
});
The div is being hid but not being shown if the Other option is selected.
Is there a different way to do this with Select2?
Edit: Forgot to mention that this a multiple select field. Also, adjusted the code and took out the this.checked as that was for a check field.
try to create a new css class, is-hidden{ display:none;}
$(document).ready(function() {
var h = $(".shipment-details--other-description");
$("#shipment-details-select-pacakage-types").change(function() {
if (this.checked && this.value == "Other") {
h.addClass('is-hidden');
} else {
h.removeClass('is-hidden');
}
}).change()
});

Using SELECT2 4.0.0 with infinite Data and filter

I'm using Select2 now since 2 years and I really enjoy all dev made. however, version 3.5.x has his limit, so I'm moving to version 4.0, which give me headaches!
For your record, I'm using Select2 with large table (> 10.000 entries), so AJAX & infinite data (page set to 50 items).
With version 3.5.2, I can reproduce the underline match when searching for data (using formatSelection and query.term). Any idea how to make it with version 4.0.0 (function templateResult only passes result and not query anymore?
With version 3.x, you can add free entries using search value was not in the list (using createSearchChoice). Version 4.0 does not have this option, any idea how to make it again?
I try to replace the Select bar with an input bar (still using the select dropdown). It seems possible to force the adapter but I was unable to find how.
I need to add either a line (at row 1) or a button (floating to the right) to add new item (similar to createTag, but for an item). has someone made it already?
I'd highly recommend reading the release notes and the 4.0 release announcement when migrating from Select2 3.5.2 to Select2 4.0.0.
With version 3.5.2, I can reproduce the underline match when searching for data (using formatSelection and query.term).. any idea how to make it with v4.0.0 (function templateResult only pass 'result' and not 'query' anymore ?
This was removed in 4.0 because the results have been separated from the queries, so it didn't make sense to keep passing along the information. Of course, this doesn't mean you can't get the query and store it. All you would need to do is store the query, something like the following might work
var query = {};
var $element = $('#my-happy-select');
function markMatch (text, term) {
// Find where the match is
var match = text.toUpperCase().indexOf(term.toUpperCase());
var $result = $('<span></span>');
// If there is no match, move on
if (match < 0) {
return $result.text(text);
}
// Put in whatever text is before the match
$result.text(text.substring(0, match));
// Mark the match
var $match = $('<span class="select2-rendered__match"></span>');
$match.text(text.substring(match, match + term.length));
// Append the matching text
$result.append($match);
// Put in whatever is after the match
$result.append(text.substring(match + term.length));
return $result;
}
$element.select2({
templateResult: function (item) {
// No need to template the searching text
if (item.loading) {
return item.text;
}
var term = query.term || '';
var $result = markMatch(item.text, term);
return $result;
},
language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
}
});
With version 3.x, you can add free entries using search value was not in the list (using createSearchChoice). V4.0 has not this option, any idea how to make it again ?
This can still be done in 4.0 using the tags option (set it to true). If you want to customize the tag, you can use createTag (similar to createSearchChoice).
var $element = $('#my-happy-select');
$element.select2({
createTag: function (query) {
return {
id: query.term,
text: query.term,
tag: true
}
},
tags: true
});
Simple way to underline matched results with select2 4.x
$element.select2({
escapeMarkup: function (markup) { return markup; }
,
templateResult: function (result) {
return result.htmlmatch ? result.htmlmatch : result.text;
}
,
matcher:function(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
var idx = data.text.toLowerCase().indexOf(params.term.toLowerCase());
if (idx > -1) {
var modifiedData = $.extend({
'htmlmatch': data.text.replace(new RegExp( "(" + params.term + ")","gi") ,"<u>$1</u>")
}, data, true);
return modifiedData;
}
return null;
}
})

Does Dart have childSelector in event function like jQuery on()?

Does Dart have childSelector in event function like jQuery on()? Because I want fire contextmenu event only if mouse hover specific element type.
This is my javascript code.
var $contextMenu = $("#context-menu");
$("body").on("contextmenu", "table tr", function(e) {
$contextMenu.css({
display: "block",
left: e.pageX,
top: e.pageY });
return false;
});
But I don't know how to check if hover "table tr" in my Dart code.
var body = querySelector('body');
var contextMenu =querySelector('#context-menu');
// fire in everywhere
body.onContextMenu.listen((e) {
e.preventDefault();
contextMenu.style.display = 'block';
contextMenu.style.left = "${e.page.x}px";
contextMenu.style.top = "${e.page.y}px";
}
You can filter events :
body.onContextMenu.where((e) => e.target.matchesWithAncestors("table tr"))
.listen((e) {
e.preventDefault();
contextMenu.style.display = 'block';
contextMenu.style.left = "${e.page.x}px";
contextMenu.style.top = "${e.page.y}px";
});
the problem is the following:
$("body") gives you a set of elements that does not change. The `.on(..., 'sub selector') however is actually bad, because it checks the subselector against the target of the event EVERY TIME for every event.
I see two solutions here:
The first is to select all children and add the event listener to all of the elements:
var body = querySelector('body');
body.querySelectorAll('table tr')... onContextMenu...
But this will not work if you insert tr into the table later.
The other way is to check the .target of your event and see if it's a tr and if its in your table. I hope this already helps. If you need more detailed help let me know!
Regards
Robert

Angularjs: jquery selectable

i have created a directive to handle selectable provided by Jquery
mydirectives.directive('uiSelectable', function ($parse) {
return {
link: function (scope, element, attrs, ctrl) {
element.selectable({
stop: function (evt, ui) {
var collection = scope.$eval(attrs.docArray)
var selected = element.find('div.parent.ui-selected').map(function () {
var idx = $(this).index();
return { document: collection[idx] }
}).get();
scope.selectedItems = selected;
scope.$apply()
}
});
}
}
});
to use in html
<div class="margin-top-20px" ui-selectable doc-array="documents">
where documents is an array that get returned by server in ajax response.
its working fine i can select multiple items or single item
Issue: i want to clear selection on close button
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
i can write jquery in controller to remove .ui-selected class but its not recommended approach
can some one guide me whats the best practice to achieve these type of issue
Update:
i fixed the issue by broadcasting event on cancel and listening it on directive
$scope.clearSelection=function() {
$scope.selectedItems = [];
$timeout(function () {
$rootScope.$broadcast('clearselection', '');
}, 100);
}
and in directive
scope.$on('clearselection', function (event, document) {
element.find('.ui-selected').removeClass('ui-selected')
});
is this the right way of doing it or what is the best practice to solve the issue.
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview

How to call Modal Dialog from Datatables row - seem to have conflict with Jquery UI

I want to create "CRUD" functions by calling a modal form by clicking on a row in Datatables.
I've been at this for hours traversing through each step of my code and it seems I'm getting a conflict between my JQ-UI and Datatables. I found several examples, including the Datatables example for "live" functions, where you can initialize a table and call a simple jquery function.
I'm using:
code.jquery.com/jquery-1.9.1.js
code.jquery.com/ui/1.10.2/jquery-ui.js
../DataTables-1.9.4/media/js/jquery.dataTables.js
This example will give me the cursor, then makes the table "jump" across the page.
Does anyone have a working example or a fiddle I can experiment with?
function openDialog() {
$("#dialog-modal").dialog({
height: 140,
modal: true
});
}
/* Init DataTables */
$('#example').dataTable();
/* Add events */
$('#example tbody tr').on('click', function () {
$('#example tbody tr').css('cursor', 'pointer');
var sTitle;
var nTds = $('td', this);
var sBrowser = $(nTds[1]).text();
var sGrade = $(nTds[4]).text();
/*
if (sGrade == "A")
sTitle = sBrowser + ' will provide a first class (A) level of CSS support.';
else if (sGrade == "C")
sTitle = sBrowser + ' will provide a core (C) level of CSS support.';
else if (sGrade == "X")
sTitle = sBrowser + ' does not provide CSS support or has a broken implementation. Block CSS.';
else
sTitle = sBrowser + ' will provide an undefined level of CSS support.';
*/
openDialog();
//alert( sTitle )
});
A little sleep and another stab at this yielded a solution that at least solves the Datatable Dialog issue, I'll have to assume that any other issues I was having lies the other add-ins that I included. So to me this is solved.
The answer was 99% in this post - thanks to the author for the great working example.
I modified their link solution, combined with Datatables "live" solution example with variables, and was able to successfully pass data to a working dialog that works with pagination as the previous link explains.
This set up would allow me to create JQuery-UI Modal Forms, pass the ID from mySQL table column, and execute the form that's handing the Server Side PHP CRUD functions I needed.
(I can't take credit for any part of this, other than time spent making sure it worked).
The working example is taken straight from Datatables "live events" example, should be easy to drop in if you remove the sAjaxsource and go with a plain Datatable..
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"bJQueryUI": true,
"bStateSave": true,
"sPaginationType": "full_numbers",
"sAjaxSource": " /*your data source page here*/ "
} );
/* Add events */
$("body").on("click", "#example tbody tr", function (e) {
e.preventDefault();
var nTds = $('td', this);
//example to show any cell data can be gathered, I used to get my ID from the first coumn in my final code
var sBrowser = $(nTds[1]).text();
var sGrade = $(nTds[4]).text();
var dialogText="The info cell I need was in (col2) as:"+sBrowser+" and in (col5) as:"+sGrade+"" ;
var targetUrl = $(this).attr("href");
$('#table-dialog').dialog({
buttons: {
"Delete": function() {
window.location.href = targetUrl;
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
//simple dialog example here
$('#table-dialog').text(dialogText ).dialog("open");
});

Resources