如何使用Javascript或jQuery在option属性中添加“selected”?

时间:2012-09-24 02:03:55

标签: javascript jquery

下面是select选项的代码,使用php从数据库生成,我尝试使用jQuery或任何javascript将selected="selected"添加到value="4"

<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>

我尝试引用此post 但仍然不能..下面是我当前的脚本:

<script>
localStorage.setItem("Select1", "Malaysia");
    $('#countryselect').find('option').each(function(i,e){
        if($(e).val() == localStorage.getItem("Select1")){
            $('#countryselect').prop('selectedIndex',i);
        }
    });
</script>

感谢。

6 个答案:

答案 0 :(得分:13)

这应该很简单,$("#countryselect").val('4')​

它会自动设置selected=selected

演示:http://jsfiddle.net/muthkum/zYRkC/

答案 1 :(得分:7)

localStorage.getItem("Select1")将返回马来西亚,$(e).val()将在每个循环中返回1,2 ... 5。所以你的情况永远不会成真。而是使用

<script>
localStorage.setItem("Select1", "4");
    $('#countryselect').find('option').each(function(i,e){
        if($(e).val() == localStorage.getItem("Select1")){
            $('#countryselect').prop('selectedIndex',i);
        }
    });
</script>

答案 2 :(得分:6)

selected属性为boolean attribute,其存在将相关DOM属性的值设置为true。如果该属性不存在,则所选属性的值为false

如果某个选项具有所选的属性,则在首次加载页面或重置控件所在的表单时,该选项将成为所选选项。

如果选项属性设置为true,则会选择该选项。但是,如果重置表单,将选择默认选择的选项(即具有所选属性的选项,或第一个选项,或无选项)。

设置所选属性(即将选项设为默认选项):

var select = document.getElementById('countryselect');
var option;

for (var i=0, i<select.options.length; i<iLen; i++) {
  option = select.options[i];

  if (option.value == '4') {
  // or
  // if (option.text = 'Malaysia') {
     option.setAttribute('selected', true);

     // For a single select, the job's done
     return; 
  } 
}

请注意,这可能不会使该选项成为当前选中的选项,它只会添加所选属性。为了确保它被选中(如果这是必需的),还将所选属性设置为true(见下文)。

请注意,setAttribute的第二个参数应该是一个用于设置属性值的字符串。但是,selected属性没有“setable”值,因此忽略第二个参数(例如,偶数false仍然会设置属性并使选项成为默认选择的选项)。这会引起一些混乱。 : - )

设置所选属性(即只选择当前所选选项):

var select = document.getElementById('countryselect');
var option;

for (var i=0, i<select.options.length; i<iLen; i++) {
  option = select.options[i];

  if (option.value == '4') {
  // or
  // if (option.text = 'Malaysia') {
     option.selected = true;
     return;
  } 
}

答案 3 :(得分:6)

从jQuery 1.6开始“要检索和更改DOM属性,例如表单元素的选中,选中或禁用状态,请使用.prop()方法。”

$("#countryselect option[value=4]").prop("selected", "selected")

答案 4 :(得分:1)

试试

$("#countryselect").val('4')
    //OR

$("#countryselect option").val('4')​.attr("selected", true)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

选中此FIDDLE

答案 5 :(得分:-1)

$('#countryselect > option[value *= "4"] ').attr('selected',true);

这将起作用