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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With