Hiding option groups (optgroups) in Chrome and Internet Explorer with Jquery

If you need to hide a series of optgroups with Jquery, it is easy to do so in Firefox: you just need to call $(this).hide() on the option group, and it and all its children will be hidden and not selectable. If you want to show them back, you just need to call $(this).show() and they will reappear.

However, other browser like Chrome and IE don’t allow this: the style rule (display:none) is applied to the element but does not work, and the elements stay visible. I’ve found out a quick workaround for this problem.

Basically, all you need to do is to

  1. disable all the options within the optgroup (and deselect them if they are selected)
  2. move the optgroup to the end of the select’s optgroups, so that it does not get in the way

If you want to reinstate that optgroup (make it selectable again), you must do the opposite:

  1. enable all the options within the optgroup
  2. move the optgroup to the beginning of the select’soptgroups, so that it is visibile again.

I’ve created a couple of custom jquery functions for the purpose:

$.fn.hideOptionGroup = function() {
 $(this).hide();
 $(this).children().each(function(){
 $(this).attr("disabled", "disabled").removeAttr("selected");
 });
 $(this).appendTo($(this).parent());

}

$.fn.showOptionGroup = function() {
 $(this).show();    
 $(this).children().each(function(){
 $(this).removeAttr("disabled" );
 });
 $(this).prependTo($(this).parent());
 $(this).parent().animate({scrollTop:0},0);
}

You apply the function to the optgroup as follows:

$("#myOptgroupId").showOptionGroup();
$("#myOptgroupId").hideOptionGroup();

What this functions do is:

  1. hide/show the element in Firefox directly.
  2. then, it disables/enables all of the optgroup’s options.
  3. and moves it to the end/beginning of the select’s optgroups.
  4. scrolls the select to the top, so that the first optgroup is shown even if the user had scrolled down and selected something else (only for the show function).

This has been tested with Chrome, will test it with Explorer soon. Hope this helps. Comments and suggestions are welcome.

4 responses

  1. Hello,

    Thanks for your script, it’s nearly perfect for me. The only problem i see is that the reminding option stay visible in chrome even if they are disabled. How to hide them and clean the select?

    Thanks.

  2. The only option to really hide them is to remove all options, save them somewhere, wipe the select options and repopulate the select only with the options you want. It is a much more complicated thing to do, I went for the simpler option.

Leave a comment