How to set default value for HTML select?
This question already has an answer here:
$(function() {
var temp="a";
$("#MySelect").val(temp);
});
<select name="MySelect" id="MySelect">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
You first need to add values to your select
options and for easy targetting give the select
itself an id
.
Let's make option b
the default:
<select id="mySelect">
<option>a</option>
<option selected="selected">b</option>
<option>c</option>
</select>
Now you can change the default selected value with JavaScript like this:
<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');
for(var i, j = 0; i = mySelect.options[j]; j++) {
if(i.value == temp) {
mySelect.selectedIndex = j;
break;
}
}
</script>
See it in action on codepen .
您应该定义选项的属性,例如seleted =“selected”
<select>
<option selected="selected">a</option>
<option>b</option>
<option>c</option>
</select>
链接地址: http://www.djcxy.com/p/88072.html
上一篇: 我想要一个复选框被默认选中,
下一篇: 如何设置HTML选择的默认值?