Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing selection is not working in select2

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

like image 704
jstuardo Avatar asked Apr 26 '16 02:04

jstuardo


4 Answers

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:

allowCreate requires placeholder option

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.

like image 197
Medet Ahmetson Atabayev Avatar answered Oct 30 '22 06:10

Medet Ahmetson Atabayev


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.

like image 35
jstuardo Avatar answered Oct 30 '22 07:10

jstuardo


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;
}
like image 2
Danny Gunawan Avatar answered Oct 30 '22 05:10

Danny Gunawan


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

Select2 4.0.3.

like image 1
Igor Muravinets Avatar answered Oct 30 '22 06:10

Igor Muravinets