Jquery set optgroup selected value

7.4k views Asked by At

I am not sure how to set the optgroup selected value, making sure the option selected has the correct label. The problem that i am having is that I have two labels but the options for each can be the same.

Label 1 = Honda Label 2 = Toyota

Options for both:

option 1 = "Red" option 2 ="Blue" ...

I want to set the selected option to Blue under the Honda label on document.ready(). Currently when i try to set the option as selected the last item using "Blue" is the one that is selected in this case that is Blue under the Toyota label.

I have tried:

var color ="Blue";
var make ="Honda";
var test = $('#car_selector optgroup[label='+make+'] option[value="'+color+'"]')
test.prop('selected', true);

<select>
 <optgroup label="Honda">
   <option value="blue">Blue</option>
   <option value="red">Red</option>
 </optgroup>
 <optgroup label="Toyota">
   <option value="blue">Blue</option>
   <option value="red">Red</option>
 </optgroup>
</select>
1

There are 1 answers

2
elzi On BEST ANSWER

Assuming you have markup similar to this:

<select>
  <optgroup label="Honda">
    <option value="blue">Blue</option>
    <option value="red">Red</option>
  </optgroup>
</select>

This JS will work:

var make = 'Honda';
var color = 'red';

var optgroup = $('select optgroup[label="'+make+'"]')
var option = optgroup.find('option[value="'+color+'"]')

option.attr('selected', true)

JSBin here

EDIT As I mentioned in comment, it was just an error properly quotating the make variable into the selector.