clearing selection is not working in select2 - jquery-select2-4

I have implemented select2 widget, version 4. It works, but the x icon. It is not clearing the selection.
If you see this doc: https://select2.github.io/options.html, it says that this a problem in fact, but the documentation is incomplete for this.
Anyone has solved this already?
Thanks
Jaime

No it's not a bug. The "X" icon requires placeholder option.
Without it, clearAllow option cannot be used. So, right code will be like this:
$(".js-example-placeholder-single").select2({
placeholder: "Put some text...",
allowClear : true
});
By the way, there is undocumented option called debug. If you pass it to select2() method, the found errors will be printed on console. For example code in below:
$(".js-example-placeholder-single").select2({
//placeholder: "Put some text...",
allowClear : true,
debug: true
});
Will get in browser's console:
Why allowClear requires placeholder option?
The real drop down list, that you create with <select> and <option> elements hides by select2. And created new one.
In the new created drop down list, the field that user see (without drop down list) created automatically. Each time when you select new option, select2 will change previous Field with new one.
When X icon clicked, it also delete main field. And creates new field with parameters of placeholder.

Finally I have found it is a bug in Select2 4.0.2.
The solution is this, in select2.js, line 1760.
This has to be replaced:
this.$element.val(this.placeholder.id).trigger('change');
this.trigger('toggle', {});
By:
this.$element.val(this.placeholder.id).text(this.placeholder.text).trigger('change');
//this.trigger('toggle', {});
This solution also causes the dropdown not to appear when selection is cleared.

In my case, the clear button is not working even placeholder option is set. I need to add z-index property:
.select2-container .select2-selection--single .select2-selection__rendered {
z-index:1;
}

Adding of the empty select option with value '' helped me.
Select2 4.0.3.

Related

I am facing issu with select2 clear function to remove manual selected option

select2 clear is not working when I am select option manually and clear t by js
Here is my function to clear select2 selected option
$('#select2_id option').removeAttr('selected');
Try this
$('#select2_id').val('').trigger('change);
Instead of
$('#select2_id option').removeAttr('selected');

CKeditor 5 (online builder) insist on having placeholder in the text field

Using the default setup using the CKeditor v5 online builder and it works, but I have a minor challenge.
The text area insist on having placeholder text inside the area. I have looked into the documentation but there is no ay to set it to false.
The actual html code does not include a placeholder-tag, so it's not to blame. Sere the attached screenshot which (sorry in Danish) includes 2 placeholders in the main text area. I have not enabled it anywhere, so why are they showing?
When inspecting the elements in a browser, there are 2 (one with the big letters and another one with the smaller letters)
Help is appreciated.
You could do the following to remove the title plugin and set the placeholder to blank:
ClassicEditor.create( document.querySelector( '.editor' ), {
removePlugins: ['Title'],
placeholder: '',
});
Well, I guess that I solved the issue my self all though it is not very logic.
I had included a plugin named 'title'.
"..Enables support for adding the title field to your document. It helps ensure that there will always be a single title field at the beginning of the document..."
All though the plugin was added I did not actively activate the function anywhere. Nor did I find any syntax to enable or disable the function. I just appeared with no option to change that.
Anyhow. I made a new package using the CKeditor 5 Online Builder and I did not select the 'title' plugin and everything was fixed.
I removed the placeholder in the CKEditor using this:
config = {
toolbar: [
'heading',
],
removePlugins: ['Title'],
}

how to change select2 value programmatically

I have a select2 box in bootstrap modal, I want to change the value of the select2 box but it didn't work.
I tried every single solution in previous posts and results but none of them got it work.
I use select2 4.0.2, I tested:
$('#select_id').val('val').trigger('change.select2');
$('#select_id').val('val').trigger('change');
$('#select_id').val('val').change()
It works one or two times then it stops working (randomly)
It works fine only when I change the select2 back to 3.x.x
$('#select_id').val('val').trigger('change');
is the right way, see here
$('#select_id').select2('val', selectedValue);
For Select2 with Ajax call, I struggled with lot of options, but none worked. Then i came to following solution, which works like charm
$("#select_id").html($("").val('val').text('text')).trigger("change");
To programmatically select an option/item for a Select2 control, use the jQuery
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
You can also pass an array to val make multiple selections:
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
I have used the following code in 4.x.xx version and it is working
$('#select_id').val('val').select2();
If you, like me, have added a custom handler for the select2:selecting event the correct complete answer to changing a value and triggering the custom select2 event would be:
$('#select_id').val('val').trigger('change').trigger({
type: 'select2:event_name', // It worked for me with select2:selecting and select2:select
params: {
args: { // Only use 'args' if using select2:selecting, select2:select does not use it
data: varWithEventData
}
}
});
For those who facing an issue like this:
If you're using multiple select elements and have a common event handler (like $(".mySelect2Inputs").click(...) ) when you do $('#mySelect2').trigger('change') the click event handler is gonna trigger multiple times ($(".mySelect2Inputs").length times).
To prevent this situation, you must use $('#mySelect2').trigger('change.select2') (attention to .select2 namespace!).
From the select2 docs:
https://select2.org/programmatic-control/events#limiting-the-scope-of-the-change-event
It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. To limit the scope to only notify Select2 of the change, use the .select2 event namespace:
$('#mySelect2').val('US'); // Change the value or make some change to the internal state $('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes

How to get select2 dropdown to scroll to selection when initially opened

When I attach jquery select2 to a <select> that already has an option selected, the dropdown does not show the selected option. If I choose a new option, close the dropdown, then re-open it, the dropdown does show the option.
Example fiddle here: https://jsfiddle.net/9tf2nx8L/1/
Steps to reproduce:
Notice "5" is selected in the markup
Click the select2 box
Notice how the list of options starts at the top
Click another option.
Click outside the dropdown, causing it to disappear
Click the select2 box again
Notice how the list of options has scrolled to have your newly selected option visible
I'm thinking this is a bug report, but wanted to sanity-check it with SO first.
There you go:
function dropscroll(){
document.getElementById($(".select2-results__options").attr("id")).scrollTop = $(".select2-results__option[aria-selected=true]").outerHeight() * $(".select2-results__option[aria-selected=true]").index() - 100;
}
$(document).on("click",".select2-container", function(){
setTimeout("dropscroll()",1);
})
You may have to do some overriding of some select2 core. The method that is invoked that scrolls to the currently selected item is the
ensureHighlightVisible()
It's located inside of the results module of select2. If you go down the route of overriding the core, you can hook into the 'results:all' event from select2 when you bind to the results module. Your code would look something like so:
[omitted code here]
YourClassThatOverridesResults.prototype.bind = function (decorated, container, $container) {
var self = this;
decorated.call(this, container, $container);
container.on('results:all', function (params) {
if (container.isOpen())
{
self.setClasses(params);
self.ensureHighlightVisible();
}
});
}
[omitted code here]
If this seems like a roundabout answer - it is. I don't know how deep down the rabbit hole you want to go, but I hope it can lead you in the right direction.

Datepicker returning uncaught typeError: undefined 'currentDay'

I've been using jQuery UI with Bootstrap and I seem to run into a problem that I haven't had before. I'm not sure what has changed; I've tried setting back different version of jQuery and I didn't update the jQuery UI in the meanwhile. So I'm not exactly sure what broke.
The error from the console when I click on any date in the datepicker returns:
Uncaught TypeError: Cannot set property 'currentDay' of undefined
The code is fairly straightforward as one would expect from a datepicker:
$(".datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
With the following HTML:
<input type="text" class="datepicker" />
Is this a bug that should be reported (since no other Google matches turn up) or is it something else I've missed?
I've found the solution. After a long time of debugging I figured out that there was a <div> that had the exact same ID, lying higher than the input field. Therefore the script took the first instance that contained the ID and picked the DIV instead of the input field.
I removed/renamed the DIV and it worked fine again.
The above jQuery datepicker error is generally caused by having a duplicate controls with the same ID, no matter whether you use id or another selector like css class or field name to instantiate it.
I solved this with create new ID for HTML DOM object. There is duplicated Id.
Try to add new ID for HTML DOM object.
I was having this error also. I found that elsewhere on the form I had some label 'for' attributes that did not match ids on the form inputs - seems like this might confuse datepicker too. Once I fixed those up, everything worked fine and the error went away. Take Andreas' advice (+1 for that!) and validate your forms - Chris Pederick's Web Developer Toolbar gives you an easy way to validate as you go.
put a selector.
<script> $("#formID #duplicatedId").datepicker({language: 'he'});
</script>
FormID: Id of the form that contains input.
duplicatedId: input element's Id.
In my case I was triggering the datepicker from a div against a hidden input field and getPos(a) was causing an undefined message on the variable "a". I experimented with moving the hidden input field outside of a div and that did the trick. Note that the input field was findable by jQuery no matter where it was, so that was not the problem - it was with positioning. Hope this helps someone else.
Might be two input box having same class without different id and for that you are trying for date picker. If it is there give two different id it will work.
I've ran into this problem too, and i was 100% sure i did not use duplicate id.
After some debugging i found out a reason - i was using DataTables mod, which duplicates contents of tfoot, thus creating exact copy of datepicker elements. And i had this datepicker inputs in tfoot row.
Fixed that issue with:
table.find("TFOOT").find("TR:first").remove();
Which is called AFTER table.DataTable(....)
This removed original, zero height row with all contents;

Resources