Set a select by option value with optgroups
Asked Answered
T

2

6

We do business in the US and Canada, so on a registration form I have a select that has optgroups to separate the US states from the Canadian provinces. I use the two character codes and store them in the database. When I want to edit the customer information, I want the same options available as on the registration form; however, I cannot seem to find the state or province by the value and then mark it selected.

Here is an example of the select:

<select id="company-state">
     <option value="">Select One</option>
     <optgroup label="United States">
          <option value="AK">Alaska</option>
          <option value="AL">Alabama</option>
          ...
          <option value="WV">West Virginia</option>
          <option value="WY">Wyoming</option>
     </optgroup>
     <optgroup label="Canada">
          <option value="AB">Alberta</option>
          <option value="BC">British Columbia</option>
          ...
          <option value="SK">Saskatchewan</option>
          <option value="YT">Yukon Territory</option>
     </optgroup>
</select>

I have tried numerous solutions, such as, trying to find the option by value or by ordinal and nothing seems to work.

Toffic answered 15/11, 2012 at 16:49 Comment(0)
A
7

Simple jQuery answer:

var value = "foo";
$('#company-state option[value="' + value +'"]');

Live DEMO

To "mark it as selected" you can add to the selector:

$('#company-state option[value="' + value +'"]').prop('selected', true);
Amaliaamalie answered 15/11, 2012 at 16:53 Comment(1)
This won't work if the same option value exists in different optgroups. In that case, it will always choose the last option.Camelback
A
0

Just set the value of dropdown using the .val operator and you are good to go. Please check the fiddle.

var value = "SK";
$("#company-state").val(value);
alert($('#company-state').val());

https://jsfiddle.net/2t48cqho/

Appling answered 21/11, 2015 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.