2012-07-26 60 views
0

我試圖訪問從下拉列表中選擇的值並填充到一行表中。我使用:在下拉列表中選擇的索引當沒有選擇任何值時拋出錯誤

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

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

如果我從下拉列表中選擇一個選項,但是如果我沒有從下拉列表中選擇任何內容,我會得到一個null值,並且會出現JavaScript錯誤。

有人可以幫助我嗎?

回答

1

獲取潛在option元素,採用了if語句,這樣你就不會嘗試訪問.text當沒有元素可用。

var selected = choiceInput.options[choiceInput.selectedIndex]; 

if (selected) 
    cell2.innerHTML = selected.text; 
0

使用驗證。

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