Tags option with allowClear, selectOnClose and ajax


I have posted a similar question before on the “How do I” section.

Basically, when the select2 I use is initialized with just selectOnClose and allowClear with data from ajax, I can just clear a selected option by clicking the ‘x’ button one time. There is no issue with this.

However, when I initialize select2 with an additional ‘tag’ property, I can only clear the new added option by clicking on the x button twice.

My JS Bin is here

It does seem like this is a bug (but I have a work-around: see the end of this post). What seems to be happening is that the first click (whether or not it’s on the X) actually opens the dropdown. The second click (on the X) deletes the selection. This is true whether you select an item that is already in the list or you enter your own new item.

However, I also noticed that if you start typing, say “red”, and then select one of the items from the list, if you then try to click the X: first it opens the overlay and removes the selection—but leaving the text you typed (in this case “red”) , then clicking the X again removes “red” and again displays the item you selected, then clicking the X a third time removes the selected item (and the entry field is finally empty).

If, however, your initial click is not on the X (i.e., it’s on the selected item text), the dropdown appears. You can then click the X to clear the selected text.

So I agree this behavior is probably a bug. I did find two ways to work around this:

  1. I commented out the minimumInputLength configuration property, so that opening the dropdown shows the first few items. In that case, whether you select an existing item or enter your own, you can clear it with a single click on the X. So it seems like that property might also be involved in the bug. If you can live with displaying the first few items of the list when it drops down, this might be a solution for you.
  2. An even better solution, which allows you to keep the minimumInputLength configuration property, is to include an empty <option> in your <select> element HTML. Doing this causes the X to work as expected:
  <select style="width:200px" id="example1">
    <option value=""></option>