Reputation: 41852
I am beginner in javascript.
js file
var msgErrorPalletizedWeight = document.getElementById('msgError');
function palletizedWeightValidation() {
console.log("hello");
/*ERROR*/ msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked with *");
}
HTML
<head runat="server">
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/file.js" type="text/javascript"></script>
</head>
<body>
<p id="msgError"></p>
<asp:Button ID="btnSubmitPalletized" runat="server" Text="Submit"
OnClientClick="palletizedWeightValidation()" />
</body>
ERROR
Cannot read property 'innerHTML' of null
I searched many sites before asking here, they all recommending to check for null before validations which I can do but my problem here is I want to add some text to the p
tag as you can see.. How to achieve that? I even tried appending, thought it might solve the problem. I know this is a silly mistake because there are many posts on this... the thing is that I cant understand where I am going wrong.
Please help.
Upvotes: 1
Views: 18411
Reputation: 3089
The important thing is when your js file gets executed. If you load js file inside head tag, your file will be executed before DOM is created. That means, document.getElementById function returns null.
Upvotes: 1
Reputation: 148180
You are trying
to access the element
of html when it is not ready
, put the statement in event function to get the element in function palletizedWeightValidation
.
function palletizedWeightValidation() {
var msgErrorPalletizedWeight = document.getElementById('msgError');
console.log("hello");
/*ERROR*/ msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked ith *");
}
EDIT To stop postback, you need to return false from javascrip function.
<asp:Button ID="btnSubmitPalletized" runat="server" Text="Submit"
OnClientClick="return palletizedWeightValidation()" />
function palletizedWeightValidation() {
var msgErrorPalletizedWeight = document.getElementById('msgError');
console.log("hello");
/*ERROR*/ msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked ith *");
return false; // returning true will cause postback.
}
Upvotes: 4
Reputation: 2166
The error you are getting is caused because you are trying to read an attribute of a NULL object. This means that your line:
var msgErrorPalletizedWeight = document.getElementById('msgError');
is not finding any elements on your page.
Upvotes: 0