eric.itzhak eric.itzhak - 9 months ago 46
HTML Question

How to set selected option by optgroup?

I have the following select :

<select name="pricelist_product[]" id="pricelist_product">
<option value="error" disabled="disabled">SELECT PRODUCT</option>
<optgroup label="Cellcom" id="1">
<option value="70">75</option>"
<option value="125">125</option>
<option value="199">199</option>
<option value="5">card bonus 5</option>
<optgroup label="Orange" id="2">
<option value="70"> 70</option>
<option value="130"> 130</option>
<option value="135"> 135 </option>

Now this is just a simplification, in reality I may have a situation in which options from different groups have the same value.

Now what I did is defer them using the ID of the
which is a nice hack but I'm encountering problems as to how I can set a selected option by group. I have the following code:

$('#prices_table tbody tr:last').children().eq(0).children()

contains the value, which of course can set the wrong one. I have a 2D array which contains the values like this:


Where the first ID is the
id and the second is the value. How can I achieve this ? I found no information on the subject.

Answer Source

Try this:

$(function() {
    var groupId = "1";
    var value = "70";

    $("#pricelist_product #'" + groupId +  "' option[value='" + value + "']").prop("selected", true);