簡體   English   中英

[HTML / JavaScript]:getElementByID無法獲得價值

[英][HTML/JavaScript]: getElementByID not getting value

我無法弄清楚為什么它不跟蹤CompanyType的值。 如果我從驗證中刪除CompanyType塊,則效果很好。 它甚至成功驗證了CompanyName,但在CompanyType上卻失敗了。

下面是代碼:

<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>

您在CompanyType select中缺少id屬性

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

應該

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

大衛·多沃德(David Dorward)就上述順序有一點。
首先是HTML,之后是<script>

最好在文檔准備好后執行JS。 考慮使用jQuery

您試圖在元素存在之前獲取它。 大多數腳本都是在HTML嘗試訪問之后。

除了其他人關於正確ID的說法外,最好訪問選擇值,如下所示:

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

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

您尚未定義CompanyType的ID,僅定義了名稱。

一切都很簡單-您嘗試通過id“ CompanyType”獲取元素,但是您的select元素具有空id,請在您的select元素中添加id =“ CompanyType”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM