Set default value using options

We do business in the USA and Canada, so in the registration form I have a choice in which there are optgroups for the US state branch from the provinces of Canada. I use two character codes and store them in a database. When I want to edit client information, I want the same parameters to be available as in the registration form; however, I cannot find the state or province by value, and then mark it.

Here is an example of a choice:

<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 tried many solutions, for example, trying to find an option by value or in order, and nothing works.

+4
source share
2 answers

JQuery simple 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); 
+5
source

Just set the value of the dropdown using the .val operator, and you're good to go. Please check the script.

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

https://jsfiddle.net/2t48cqho/

+1
source

Source: https://habr.com/ru/post/1446285/


All Articles