atultherajput
atultherajput

Reputation: 175

JavaScript is throwing error "Uncaught TypeError: Cannot set property 'value' of null" yet element is present

I am working on on jsp. I have an <input> element in jsp file. But when I am tring to set value of <input id="digipan" name="digipan" type="hidden" value="" ></input> using javascript I am getting this error: "Uncaught TypeError: Cannot set property 'value' of null". This is my html code:

<div class="col-xs-12 contactDetails">
        <div class="col-md-6">
           <mark>PAN Card</mark>
            <div >
               <label style="color: red">Choose File:</label> 
               <div class="form-group">
                 <input type='file' id="PAN_Card" name="PAN_Card" /> <div id="dl_pan"> OR <div class="share_fm_dl" id="attachment_poi" ></div></div>
               </div>
               <div id="digipanfile" name="digipanfile"></div>
               <input id="digipan" name="digipan" type="hidden" value="" ></input>
             </div>
       </div>
    </div>

And this is my Javascript code:

document.getElementById('digipanfile').innerHTML = "File:<a href=" + response + ">" + filename + "</a>";
        document.getElementById('digipan').value = response;
        document.getElementById('PAN_Card').style.display = 'none';

This javascript code is inside a function which is executed only after page load. Also, View Page Source is showing this <input> tag but Inspect Element is not showing it. Note:- I am already using jQuery document ready method but still having this error.

Upvotes: 0

Views: 1623

Answers (2)

Gururaj
Gururaj

Reputation: 11

Its good practice to trigger all your script's after your DOM get's fully loaded. As alexleo2000 mentioned you can wrap your script function's in window.load(function() { //here goes your script function })

Upvotes: 0

alexleo2000
alexleo2000

Reputation: 157

You have to wait till the document is loaded. So you should use the "load" eventlistener in your javascript file:

window.addEventListener("load", e => {
        document.getElementById('digipanfile').innerHTML = "File:<a href=" + response + ">" + filename + "</a>";
        document.getElementById('digipan').value = response;
        document.getElementById('PAN_Card').style.display = 'none';
    })

You could also use the jQuery methods window load and document ready. Both occur roughly at the same time. If you want to know which one of them fires first you should run this code to know:

$(document).ready(function() {
      alert("document ready occurred!");
});

$(window).load(function() {
      alert("window load occurred!");
});

Upvotes: 3

Related Questions