l-qdig
Last Updated: February 25, 2016
·
2.944K
· jeremybass
55c20cf75c7199b6e652014dd5e9d361

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() {
    $.each($(this),function(i,v){
        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
        if($("."+lable+"_contaner_"+pindex).length<=0){
            $("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"); });
        optgroup.appendTo(hidden);
    });
}

$.fn.showOptionGroup = function() {
    $.each($(this),function(i,v){
        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(){
    $(this).find('option').attr("selected",false);
    $(this).find('optgroup').hideOptionGroup();
    var pname = $(this).closest('select').attr("name");
    $('optgroup.'+val+'s[data-pname="'+pname+'"]').showOptionGroup();
});

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.

Cheers

Say Thanks
Respond