使用optgroups设置一个select by选项值 [英] Set a select by option value with optgroups

查看:197
本文介绍了使用optgroups设置一个select by选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在美国和加拿大做生意,所以在一份注册表格中,我有一个选择组织,将美国各州与加拿大各省分开。我使用这两个字符代码并将它们存储在数据库中。当我想编辑客户信息时,我需要与注册表单中相同的选项;但是,我似乎无法通过该值找到州或省,然后将其标记为选中状态。



以下是一个选择示例:

 < select id =company-state> 
< option value =>选择一个< / option>
< optgroup label =美国>
< option value =AK>阿拉斯加< / option>
< option value =AL>阿拉巴马州< / option>
...
< option value =WV>西弗吉尼亚州< / option>
< option value =WY>怀俄明< / option>
< / optgroup>
< optgroup label =Canada>
< option value =AB>艾伯塔< / option>
< option value =BC>不列颠哥伦比亚省< / option>
...
< option value =SK>萨斯喀彻温省< / option>
< option value =YT>育空地区< / option>
< / optgroup>
< / select>

我尝试过很多解决方案,例如试图通过值或序数找到选项,似乎工作。

解决方案

简单的jQuery答案:

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

现场演示



要将其标记为已选定,您可以添加到选择器中:

  $('#company-state option [value =''+ value +''')。prop('selected',true); 


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.

解决方案

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);

这篇关于使用optgroups设置一个select by选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆