michael
michael

Reputation: 1577

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...

Upvotes: 2

Views: 1891

Answers (2)

David Alpert
David Alpert

Reputation: 3177

also, you could check the target in your optgroup click handler, and short-circut if the event's target is actually an option tag, like so:

$("optgroup").click(function(e) {
   if ($(e.target).is('option')) return;
   $(this).children().attr('selected','selected');
});

Upvotes: 2

Oli
Oli

Reputation: 239820

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();
});

Upvotes: 3

Related Questions