Workaround: jQuery Select2 doesn’t let user to select option after unselect when maximumSelectionSize is used

jquery-v3I am using jQuery Select2 plugin, for select boxes, on one of my projects. The best thing I like about this plugin is that it allows the user to search through a multiple select box. Also the user doesn’t have to use the (CTRL+Click) combination to select multiple options. But today, I just came across a problem when I was trying to limit the number of options a user could select. I wanted the user to select only a single option on the multiple select box. And thankfully, Select2 has something called maximumSelectionSize which we can simply pass to the constructor. (I know I could use single select box instead of multiple but I didn’t want to change the html as all of our form elements were being created on the fly by our custom built php functions.)

$("select").select2({
		width:'100%',
		maximumSelectionSize: 1 
	})

 

Everything was working fine except one thing. When the user unselects the option which was selected earlier, Select2 doesn’t allow to select any option again. And keeps displaying ‘You can only select 1 item‘.  This looked totally weird. I don’t know whether I missed something or its an actual issue.

Select2 Error: You can only select 1 item

 

Workaround:

I searched all over the internet and found no solution to this. So I came up with a dirty workaround 😛 . I just re-initialised Select2 after any option gets unselected by using the ‘select2-removed’ event handler.

$("select").select2({
		width:'100%',
		maximumSelectionSize: 1 
	}).on('select2-removed', function(){
	$(this).select2({
		width:'100%',
		maximumSelectionSize: 1
	         });
        });

 This is only a workaround and I believe there’s a better solution to this problem. Please let me know if I did something wrong in the first place or if you have a better solution. Thanks for reading. 🙂

Leave a Reply