下拉列表中的选定索引在未选择任何值时引发错误

selected index in dropdown list throwing error when no value is selected

本文关键字:任何值 选择 错误 索引 下拉列表      更新时间:2024-02-16

我正在尝试访问从下拉列表中选择的值,并填充到表的一行中。我正在使用:

cell2.innerHTML = choiceInput.options[choiceInput.selectedIndex].text; 

其中choiceInput是我的下拉元素的名称。

如果我从下拉列表中选择了一个选项,这是有效的,但如果我没有从下拉列表选择任何内容,我会选择一个null值,并得到一个JavaScript错误。

有人能帮我吗?

获取潜在的option元素,使用if语句,这样在没有可用元素时就不会尝试访问.text

var selected = choiceInput.options[choiceInput.selectedIndex];
if (selected)
    cell2.innerHTML = selected.text; 

使用验证。

function validateListBox(){
var listBoxSelection=document.getElementById("choiceInput").value;
if(listBoxSelection==0){
alert("Please select );
return false;
}else{
return true;
}
return true;
}