2009-10-29 53 views
0

我無法弄清楚它爲什麼不跟蹤CompanyType的值。如果我從驗證中刪除了CompanyType塊,它運行良好。它甚至可以成功驗證CompanyName,但在CompanyType中失敗。[HTML/JavaScript]:getElementByID未獲得價值

下面是代碼:

<script type="text/javascript> 

//Check Company Name 
if (document.getElementById("CompanyName").value == "") 
{ 
    alert("Please enter company name"); 
    document.getElementById("CompanyName").focus(); 
    return false;        
} 

//Check Company Type       alert(document.getElementById("CompanyType").value); 
if (document.getElementById("CompanyType").value.substr(0,6) == "Select") 
{ 
    alert("Please select company type"); 
    document.getElementById("CompanyType").focus(); 
    return false;        
} 
</Script> 

以下行遵循HTML代碼的文件中:

<td align="left" valign="top"> 
<input maxlength="40" size="22" name="CompanyName" id="CompanyName" style="width:150px;"> 
</td> 
</tr> 
<tr> 
<td height="38" colspan="2" valign="middle" id="form"> 
<span class="red">*</span> 
<span class="style2">Company Type:</span> 
</td> 

<td align="left"> 
<select id=" " class="style3" size="1" name="CompanyType" style="width:150px;">                  <option value="" selected="selected">Select One</option>                    </select></td> 

回答

3

你缺少id屬性CompanyType select

<select id=" " class="style3" size="1" name="CompanyType" style="width:150px;"> 
      ^^^ 

應該

<select id="CompanyType" class="style3" size="1" name="CompanyType" style="width:150px;"> 

和戴維·多沃德有關於上述的規程。
HTML先,<script>之後。

最好在文檔準備好的時候執行JS。考慮使用jQuery

+0

非常抱歉。它在原始代碼中。 – RKh 2009-10-29 11:08:35

+1

那麼David Darward的回答就是你的解決方案。確保在創建對象時調用對象,而不是之前。 – 2009-10-29 11:10:46

+0

@Michal:感謝您的寶貴意見。我正在相應修改。 – RKh 2009-10-29 11:17:22

2

您正試圖獲得該元素存在之前。大多數腳本是在它嘗試訪問的HTML之後。

+0

@David:請解釋。 – RKh 2009-10-29 11:09:27

+0

'getElementById(「CompanyName」)'在創建ID爲'CompanyName'的元素之前被調用。 – Amarghosh 2009-10-29 11:27:49

0

您尚未爲CompanyType定義一個id,只有一個名稱。

1

除了由他人正確的ID說,這是更好地進入選擇值如下:

var select = document.getElementById("CompanyType"); 

if (select[select.selectedIndex].value.substr(0,6) == "Select") { 
    // something here 
} 
0

一切都很簡單 - 你想了解我的ID「CompanyType」元素,但你的選擇元件空ID,在您的select元素中添加id =「CompanyType」