I have a select box in which i can select multiple options. In the select box are multiple optgroups. Is there an easy way to select a whole optgroup at once in javascript?
I suggest using jQuery (or another framework) to quickly handle DOM selections. Give each optgroup a class to make it easier to grab it.
$("optgroup.className").children().attr('selected','selected');
If you want to select the entire group based on the user selecting the group, do the following:
$("optgroup.className").select(function(e) {
$(this).children().attr('selected','selected');
});
**Both examples are untested pseudo-code, but they should work with minimal changes, if necessary.
If you cannot use a framework, you'll have to traverse the DOM yourself to find the optgroup and children. You could attach a listener to the select
element to grab the element being selected then traverse to the children that way, too.