Adding a button to select2 to close when closeOnSelect is false

Hi All I’ve got this example on jsfiddle https://jsfiddle.net/sm1fo5d0/7/
What I have done is add a button to select2:open so when it opens it shows a close button. I would like my user to be able to select multiple items and then close the drop down by select close. How ever it seems to close after every selection which is pretty annoying. If anyone should shed some light on the issue I’d be grateful.

Why are you trying to change how a select box works? You’re changing a UI component that everyone already knows how to use, without any obvious benefit.

If you want to allow multiple selections, you need to specify the multiple attribute on your select HTML element. Right now you’ve got a single select, which cannot accept multiple selections. Just fixing that should get you the desired behavior (letting the user make multiple selections). I would strongly advise you to stick with the standard interface so you don’t confuse your users. (Also, if accessibility is a concern, trying to hack your own unique UI means j you will need to do the work to make it accessible, since users of assistive technology won’t know how your new UI works).

Hi John.
Thanks for the speedy response. My bad I copied the select from w3c, of course my select is more complicated with ajax loading etc. You were right I was missing the multiple attribute from the select. The fiddle has been updated to reflect the actual problem.
If you run the fiddle it works fine, then uncomment the a.tigger line 14 you will see it closes after each selection. My code should only be closing it on the appended close.

Latest fiddle is https://jsfiddle.net/sm1fo5d0/7/

While I still disagree with including the “Close” button in the dropdown at all, the reason that uncommenting the a.trigger('close'); line causes the dropdown to close whenever you click on the options is because you’re attaching the click handler to the entire $results.parents() jQuery element collection.

Keep in mind that when you chain jQuery method calls, each one returns the initial jQuery collection unless one of the chained methods alters it (i.e. is one of jQuery’s DOM traversal methods). In your code, the collection starts out as a.$results, but then changes to the .select2-results parent element (via the .parents() call). That collection persists for the rest of the method chain—including the on('click', ...) method. (In particular, inserting/appending DOM elements does not alter the current collection.)

So, you need to change the jQuery element collection to the button you’ve just inserted before attaching the click handler. If you want to do this within your current method chain, just insert a .find('.select2-close > button') call between the .append() and .on('click', ...) calls. The .find() will change the jQuery collection to just the button, and the .on() will attach the click handler to that button only.