[HTML/JavaScript]: getElementByID not getting value
I am not abl开发者_开发百科e to figure out why it is not tracing value for CompanyType. If I remove the CompanyType block from verification, it works well. It even successfully verifies CompanyName, but it fails at CompanyType.
Below is the code:
<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>
Following lines follow in the HTML code in the file:
<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>
You are missing id attribute in CompanyType select
<select id=" " class="style3" size="1" name="CompanyType" style="width:150px;">
^^^
should be
<select id="CompanyType" class="style3" size="1" name="CompanyType" style="width:150px;">
And David Dorward has a point with regards to the order of the above.
HTML first, <script>
after.
Best to execute JS when the document's ready though. Consider using jQuery.
You are trying to get the element before it exists. Most the script so it is after the HTML that it tries to access.
In addition to the said by others about correct ID it is better access select values as follows:
var select = document.getElementById("CompanyType");
if (select[select.selectedIndex].value.substr(0,6) == "Select") {
// something here
}
You haven't defined an id for CompanyType, only a name.
Everything is simple - you trying to get element by id "CompanyType", but your select element has empty id, add id="CompanyType" in your select element
精彩评论