gpt4 book ai didi

javascript - 查看 dropdownList 中的项目是否已被选择

转载 作者:行者123 更新时间:2023-12-02 20:13:49 25 4
gpt4 key购买 nike

我想知道最好的方法是什么,循环遍历 html 中的下拉列表以查看是否已选择某个项目。

我知道在 C# 中它会类似于

int selected = cmbFamily.SelectedIndex;

for (int loop = 0; loop < cmbFamily.Items.Count; loop++)
{
if (selected == -1)
{
MessageBox.Show("please select an item", "Please", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}

我将如何使用 javascript 来完成此操作?

<tr style="font-size:12pt; font-weight:bold; color:#FFFFFF; font-family:High Tower Text;">
<td>Family to join:</td>
<td><select name="drpFamily">
<option/>-select-
<option/>Gambino
<option/>Genovese
<option/>Lucchese
<option/>Colombo
<option/>Bonanno
</select><font color="red">*</font></td>
</tr>

亲切的问候阿里安

最佳答案

首先你的 HTML 代码是完全错误的。它不是</option>text ,就是<option>text</option>

要循环选择选项,就这么简单

//var options = document.getElementById("selectId").options;
var options = document.formName.selectName.options;
for(var i=0;i<options.length;i++){
if(options[i].selected){
alert(options[i].value);
}
}

但不需要循环单个选择。最简单的方法就是对单个选择使用选定的索引。

//var sel = document.getElementById("selectId");
var sel = document.formName.selectName;
var opt = sel.options[sel.selectedIndex];
alert(opt.value);

关于javascript - 查看 dropdownList 中的项目是否已被选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6610411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com