I'm unable to access the variable in the JS file.
The Validation is working fine when written in the same page. But when I pasted the Validation code to a separate JS file, its not working.
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="Scripts/NewValidation.js" type="text/javascript"></script>
<table id="tblUpdateReg">
<thead>
<tr>
<td>
Update Details
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div>
Username :
</div>
</td>
<td>
<input type="text" runat="server" id="txtUsername" />
</td>
</tr>
</tbody>
</table>
</asp:Content>
JS file:
function Validate() {
var username= document.getElementById("txtUsername").value;
if (username== "") {
alert("username Required.");
return false;
}
return true;
}
Error:JavaScript runtime error: Unable to get property 'value' of undefined or null reference
I'm unable to access the variable in the JS file.
The Validation is working fine when written in the same page. But when I pasted the Validation code to a separate JS file, its not working.
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="Scripts/NewValidation.js" type="text/javascript"></script>
<table id="tblUpdateReg">
<thead>
<tr>
<td>
Update Details
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div>
Username :
</div>
</td>
<td>
<input type="text" runat="server" id="txtUsername" />
</td>
</tr>
</tbody>
</table>
</asp:Content>
JS file:
function Validate() {
var username= document.getElementById("txtUsername").value;
if (username== "") {
alert("username Required.");
return false;
}
return true;
}
Error:JavaScript runtime error: Unable to get property 'value' of undefined or null reference
Share Improve this question asked Aug 29, 2013 at 6:36 PearlPearl 9,4558 gold badges45 silver badges60 bronze badges 1- 1 Are you calling validate function after the above content has been loaded ? – Voonic Commented Aug 29, 2013 at 6:38
1 Answer
Reset to default 1It means that the element with an id of txtUsername doesn't exist. You execute your script before the element is created.
You should either put your script at the bottom of the page or use a
window.onload = function() {}
in which you'll execute your code.