Search code examples
htmloptgroup

optgroup select title of group


I want to create a drop-down box with grouped items. It is for a database lookup HTML form that I am working with. Is there a way that I can select the group title, resulting in selection of all items in that particular group? For example, if the group title is 'German Cars' and has the items 'Mercedes' and 'Audi', on clicking 'German Cars', both German car companies should get selected.


Solution

  • If you give your opt-groups a class you can select the class then access its children.

    $('.german-cars').children();
    

    If that's unavailable the alternative is a little slow. When you loop through all the optgroups and compare their text individually then grab that ones children.

    edit: Fix selector. And elaborating:

    Then to select them on click you'd use:

    $('.german-cars').click(function(e) {
        e.preventDefault();
        $(this).children().attr('selected', 'selected');
    });
    

    Assuming the element is set to multiple selection. Otherwise only the last car in the list would get selected.

    EDIT 2

    Fiddle: http://jsfiddle.net/mbChZ/25/

    These changes should work the way you're looking for.

    $(function() {
        $('select optgroup').mousedown(function(e) {
            e.preventDefault();
            if ($(this).children(':selected').length == $(this).children().length) {
                $(this).children().attr('selected', null);
            } else {
                $(this).children().attr('selected', 'selected');
            }
        });
        $('select option').mousedown(function(e) {
           e.stopPropagation();
           e.preventDefault();
           $(this).attr('selected', ($(this).is(':selected'))? null : 'selected');                    
        });
    });​
    

    I've changed the events to mousedown so we can see the state of the elements before the browser has already handled the mousedown event. This allows us to check if they're all selected and if so deselect rather than select. And the same had to be done for the click event of the option so that it can prevent propagation on that event.

    I'm not 100% sure of the browser compatability on this one though you may want to make sure it works in older IE's if you support them.