2

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?

3
  • Is the jQuery tag correct?
    – JSelser
    Commented Sep 24, 2015 at 10:11
  • 1
    Did you tried to place your javascript bellow HTML (before closing body tag)?
    – sinisake
    Commented Sep 24, 2015 at 10:12
  • 1
    Because the element doesn't exist at the point you execute your code (you literally output the input field AFTER the javascript code has run). Use an onload event.
    – h2ooooooo
    Commented Sep 24, 2015 at 10:12

3 Answers 3

7

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>
1
  • Can happen to anyone :) I will update the answer with the option to also move the script below the element definitions. Commented Sep 24, 2015 at 10:22
2

Your script should be excuted after inputs being added to DOM. The most crossbrowser way to make your script work, is to move it just before your <body> tag is closed, and wrap it into an immediate function:

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

This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.

-1

Here your script should be after html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.