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 was trying to do something similar just now.
I wanted to select an 's
s upon clicking the group's label. The first attempt went like this:
$('select > optgroup').click(function () {
$(this).children().attr('selected', true);
});
This solution half worked...
Upon clicking the 's label all of its children became selected.
BUT when simply clicking an it was still selecting all the other
s in the group! The problem was event bubbling, because the
is inside the
technically you're clicking it too.
Therefore the final piece of the puzzle was to suppress the event bubbling upwards in the event that an was actually clicked instead. The final solution then became:
$('select > optgroup').click(function () {
$(this).children().attr('selected', true);
});
$('select > optgroup > option').click(function (e) {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
});
Job done!
EDIT
Infuriatingly this doesn't work work in IE8 (and doubtful < IE8 - maybe IE9?)...
It decides to totally ignore click events on both and elements. The only alternative that I can think of is to position elements above the optgroup labels to capture the click, but its probably not worth the effort...