Chosen, Multiselect & Limiting Selected Options on Mobile Devices

I use Chosen jQuery plugin to style and make multiple select (multiselect) dropdowns more user-friendly in my ProfilePress plugin.

One limitation of Chosen is, it is disabled on iPhone, iPod Touch, and Android mobile devices with the default select display shown instead.

Chosen has support for limiting the number of options that can be selectable but HTML select element do not. Since chosen is disabled on mobile devices, I needed to make native HTML select to support limiting selectable options.

I was able to achieve this with the JavaScript code below.

jQuery(function($) {
   $('select.pp_chosen').chosen({width:'100%', max_selected_options:3});
   // handle mobile selection edge case.
   var selector = $('select.pp_chosen');
   var last_valid_selection = null;
     selector.change(function(event) {
       if ($(this).val().length > 3) {
         $(this).val(last_valid_selection);
       } else {
         last_valid_selection = $(this).val();
       }
     });
 });

Code credit: http://stackoverflow.com/a/30475067/2648410

Don’t miss out!
Subscribe to My Newsletter
Invalid email address