Search code examples
jqueryhtmloptgroup

jQuery: Easy way to quick select a whole optgroup in select box


I use a jQuery function similar to the one in this thread: Easy way to quick select a whole optgroup in select box

But, when I click an <option> now it selects the whole optgroup, as the optgroup encloses the option elements. I use the following snippet:

  $("optgroup").click(function(e) {
    $(this).children().attr('selected','selected');
  });

my HTML looks like this:

<optgroup label="Abc">
<option value="8" >Ab</option> 
<option value="7" >C</option></optgroup>

So clickig on <option>C</option> selects <option>Ab</option> as well. Perhaps I am missing something obvious...


Solution

  • I could be wrong but you might need to add a handler to the <option>s to stop the click event bubbling up.

    Something as simple as this might help:

    $("optgroup option").click(function(e) {
        e.stopPropagation();
    });