Last Updated: February 25, 2016
· jeremybass

cross browser jquery hidden optgroup

This is here more for reference to a solution done, just for me to comeback to for ideas.

What this does is provide a simple way to hide optgroups in all browsers. Internet Explorer and Chrome seem to have the same flaw that makes it hard to hide an optgroup on for example a change event. Here is a simple flex able solution that should let you scale. Currently I use this in my CHAI HIV project.

$.fn.hideOptionGroup = function() {
        var optgroup = $(this);
        var lable= optgroup.attr("label");
        var pname = optgroup.closest("select").attr("name");
        var pindex = $("select").index(optgroup.closest("select"));
        optgroup.attr("data-pname",pname); //oddly you can't set data on an optgroup
            $("body").append("<select style='position:absolute;top:-9999em;left:-9999em;' class='"+lable+"_contaner_"+pindex+"'><select>");
        var hidden = $("."+lable+"_contaner_"+pindex);
        optgroup.children().each(function(){ $(this).removeAttr("selected"); });

$.fn.showOptionGroup = function() {
        var _lable=$(this).attr("label");
        var pname = $(this).data("pname");
        $(this).appendTo($( "select[name='"+pname+"']" ));

In my case I used it like

$.each( $('form select.property_selector,form select[name="selected_properties"]') ,function(){
    var pname = $(this).closest('select').attr("name");

The way this works is to remove the option group from the parent select element, and $.appendTo a tagged and safely hidden select element. This way we have tied the new hidden element to the original select element with out risk of any stray post variables and bypassed the cross browser issue with hiding a option group(optgroup) from a select.

Not saying this is ideal as it is a reference, but the point is that one option to hide a optgroup, is by removing it from the dom and putting it in a new dom element that is it's self hidden. This is a safe and tested solution.