I have dropdown list on my aspx page. I want to mannually set the selected value which in exist in the dropdown list. this value i am getting in var. i want to set this value as selected value when page get initialize. I want this in javascript. is there any property for dropdown as ddp.SelectedValue='40'..? here I don't know the i开发者_如何学运维ndex of 40 in the list.
selectedIndex
is a property of HTMLSelectElement so you can do the following:
<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1; // Selects option "One"
</script>
And given an OPTION element, you can get its index using the index
property:
<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index); // alerts "1"
</script>
I want to manually set the selected value
Iterate the select
's options list to get the option
you were interested in and set selected
on it:
var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
if (options[i].value==='40') {
options[i].selected= true;
break;
}
}
this will select the first option with a matching value. If you have more than one option with the same value, or a multiple-select, you may need different logic.
This:
document.getElementById('ddp').value= '40';
is specified by HTML5 to do the same, and has worked in most modern browsers for ages, but still fails in IE, unfortunately (even IE9).
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
<script language="JavaScript">
$(function() {
quickSelect();
// Handler for .ready() called.
});
function quickSelect() {
var bnd = "40";
if (bnd != "") {
$("#ddp option[value='" + bnd + "']").attr("selected", "selected");
}
}
</script>
精彩评论