eric.itzhak eric.itzhak - 1 month ago 11
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>
<optgroup label="Orange" id="2">
<option value="70"> 70</option>
<option value="130"> 130</option>
<option value="135"> 135 </option>
</optgroup>
</select>


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
optgroup
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()
.val(item.product_id).attr('selected','selected');


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

values[item.provider_id][item.product_id]


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

Answer

Try this:

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

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