2012-09-24 74 views
7

下面是选择选项的代码,并使用从数据库PHP生成和我尝试使用jQuery或任何JavaScript添加selected="selected"value="4"如何使用Javascript或jQuery在选项属性中添加“selected”?

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

谢谢。

回答

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> 
+0

谢谢,你的解决方案对我来说是有用的.. – rusly

+0

@rusly,欢迎你 –

1

试试看

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

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

入住这FIDDLE

+1

你的意思是'$(“#countryselect option [value = 4]”)。attr(“selected”,true)'? – undefined

-1
​​

这将工作

+0

http://www.tutorialspoint.com/jquery/jquery-quick-guide.htm – Rahul

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的第二个参数应该是用于设置属性值的字符串。但是,所选属性没有“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; 
    } 
} 
5

在jQuery 1.6的“检索和更改DOM性质如被检查的,所选择的,或禁用形式元素的状态,使用.prop()方法。 “

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

这工作非常棒。干杯! –

相关问题