使用 JavaScript 选择下拉菜单选项
我有一个下拉菜单,但我不知道如何让 JavaScript 函数选择下拉菜单选项。我已经测试了变量的输出,它们都是正确的,但单击时仍然不会选择该选项。这是功能和下拉菜单。
功能
function formFill(a, b, c){
theform.from.value = a;
theform.to.value = b;
for(var i = 0;i < document.getElementById("stateSelect").length;i++){
if(document.getElementById("stateSelect").options[i].value == c ){
document.getElementById("stateSelect").selected = true;
}
}
}
菜单项
<select id="stateSelect" name="stateSelect">
<option value="none">(None)</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
I have a dropdown menu and I cannot figure out how to make a javascript function select a drop down menu option. I have tested the output of the variables and they are all correct, but it still will not select the option when clicked. Here is the function and drop down menu.
Function
function formFill(a, b, c){
theform.from.value = a;
theform.to.value = b;
for(var i = 0;i < document.getElementById("stateSelect").length;i++){
if(document.getElementById("stateSelect").options[i].value == c ){
document.getElementById("stateSelect").selected = true;
}
}
}
Menu item
<select id="stateSelect" name="stateSelect">
<option value="none">(None)</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将以下行:
document.getElementById("stateSelect").selected = true;
更改为:
document.getElementById("stateSelect").selectedIndex = i;
Change the line that reads:
document.getElementById("stateSelect").selected = true;
to:
document.getElementById("stateSelect").selectedIndex = i;
替代。您可以将 selected 设置为实际选项: select.options[i].selected = true;
Alt. you can set selected to the actual option: select.options[i].selected = true;
例如,使用 Stimulus,我们获取用户的时区,然后在下拉列表中自动选择它
With Stimulus, for instance we fetch the user's time zone and then we auto-select it in the dropdown