Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  160] [ 6]  / answers: 1 / hits: 16610  / 9 Years ago, thu, september 24, 2015, 12:00:00

Before you downvote, I've read a lot of questions and it didn't help me.
My Javascript's alert returns null even when there is a value in the input type.



Here's the code :-



<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById(p0002).value;
}
else {
var str = null;
}
alert(str);
</script>

<input type=hidden name=p0002 id=p0002 value=1 >
<input type=hidden name=p0003 id=p0003 value=0 >
<input type=hidden name=p0004 id=p0004 value=2 >


It always returns null. The error in console says :




Uncaught TypeError: Cannot read property 'value' of null




Trying to fix it since last 1 hour. What is wrong here?


More From » javascript

 Answers
20

Wrap your JavaScript in window.onload. Currently your JavaScript is executing before the element exists:



<script>
window.onload = function () {
if (document.getElementById('p0002') != null) {
var str = document.getElementById(p0002).value;
}
else {
var str = null;
}
alert(str);
}
</script>


Another thing you can do is move the script tag to be after the elements you're referencing:



<input type=hidden name=p0002 id=p0002 value=1 >
<input type=hidden name=p0003 id=p0003 value=0 >
<input type=hidden name=p0004 id=p0004 value=2 >
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById(p0002).value;
}
else {
var str = null;
}
alert(str);
</script>

[#64943] Tuesday, September 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
marcos questions
Thu, Feb 24, 22, 00:00, 2 Years ago
Sat, Apr 17, 21, 00:00, 3 Years ago
Mon, Feb 1, 21, 00:00, 3 Years ago
Tue, Jan 26, 21, 00:00, 3 Years ago
Wed, Jan 6, 21, 00:00, 3 Years ago
;