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>
Assuming you have markup similar to this:
This JS will work:
JSBin here
EDIT As I mentioned in comment, it was just an error properly quotating the
make
variable into the selector.