clearing selection is not working in select2

jstuardo picture jstuardo · Apr 26, 2016 · Viewed 7.9k times · Source

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

Answer

Medet Ahmetson Atabayev picture Medet Ahmetson Atabayev · May 5, 2016

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.