2009-12-16 21 views
1

我有一個HTML下拉控件。我想檢查一下,如果其中的文本是「選擇」,它必須顯示錯誤信息。我正在使用以下代碼來執行此操作,但它不起作用。檢查HTML DropDown選項

if (document.getElementById("StudentCountry").value == "Select") 
    { 
     alert("Please select your country."); 
      document.getElementById("StudentCountry").focus(); 
      return false;        
    } 
+1

請您發佈HTML/PHP /無論代碼? – Zeemee 2009-12-16 12:17:46

回答

4
var box = document.getElementById("StudentCountry"); 
if(box.options[box.selectedIndex].text == "Select") 
+0

這可能不是「最佳」解決方案,但代碼可以複製/粘貼並隨時可以使用。 – Tubbe 2009-12-18 08:11:40

5
document.GetElementById("StudentCountry").SelectedIndex=0; 

function getDropDownListvalue() 
{ 
    var IndexValue = document.GetElementById("StudentCountry").selectedIndex; 
    var SelectedVal = document.GetElementById("StudentCountry").options[IndexValue].value; 
    alert(SelectedVal); 
} 

檢查所選值= 「選擇」

0

這是怎麼javascript代碼嵌入在HTML文件?它只是在一個腳本元素中,而不是在一個獨特的功能?如果是這樣,那麼這個函數可能總是返回null,因爲下拉菜單在使用時不會被加載。否則,代碼應該工作。只需放入一個函數,讓我們說checkCountry()並將其添加爲onchange =「checkCountry();」到標籤。 可能會破壞您的代碼的第二件事是檢查「選擇」文本。如果您檢查某個選項的值,它很可能會檢查值屬性,如: 選擇 而在此示例中,select全部寫成小寫,而不會與您的==相比較。

我希望這會有所幫助。

+0

它在不同的功能。 – RKh 2009-12-16 12:32:11

0

你的代碼似乎是完美的。檢查onceagain默認選項的值是 「選擇」 或不..

<html> 
    <head> 
    <script language="javascript"> 
     function validate(){ 
      alert('ddddddddddd ='+document.getElementById("StudentCountry").value); 
      if (document.getElementById("StudentCountry").value == "select") 
      { 
       alert("Please select your country."); 
       document.getElementById("StudentCountry").focus(); 
       return false;              
      } 
     return false; 
     } 
     </script> 

     </head> 


     <body> 
     <select id="StudentCountry"> 
       <option value="select" >---------Please Select ---------</option> 
       <option value="India" >India</option> 
       <option value="USA" >UAS</option> 
       <option value="UK" >UK </option> 
     </select> 

    <a onclick="javascript:validate();" href="#">click here to validate</a>