Select2 on existing select-dropdown

I had some issues with using Selct2 on an already existing select where the select attribute was already set. The problem was Select2 didn’t unselect the previously set option. To by-pass that I did this workaround.

To use Select2 check their installation guide here. When that is setup I used this jquery snippet where I;

  1. temporary save the previously set option
  2. removing that attribute from option
  3. init Select2 to the select element
  4. set the saved option again with the Select2 .val() function
jQuery(document).ready( function($) {
  
  // temporary save the current selected option
  selected = $("#my_select option:selected").val(); 
  
  // remove selected attribute to make default selected work
  $("#my_select option:selected").removeAttr("selected");
    
  // init select2
  $("#my_select").select2({
    minimumResultsForSearch: -1,
    multiple: false
  });

  // set default value again
  $("#my_select").val(selected); 

})

This is an example of previous select snippet where the second option is pre-selected.

<select id="my_select">
  <option value="my-first">First option</option>
  <option value="my-second" selected="selected">Second option</option>
</select>