[javascript] Uncaught TypeError: Cannot read property 'value' of null

I'm getting error in this code, I'm trying to do an event where in when the page is load, it will do the event. But the problem is when I go to other function, but same page, it gets a error of null on that variable. It has no problem when I execute this codes, but when I'm on other part of my codes this error occurs.

Uncaught TypeError: Cannot read property 'value' of null

$(document).ready(function(){


      var str = document.getElementById("cal_preview").value;
      var str1 = document.getElementById("year").value;
      var str2 = document.getElementById("holiday").value;
      var str3 = document.getElementById("cal_option").value;


        if (str=="" && str1=="" && str2=="" && str3=="" )
          {
            document.getElementById("calendar_preview").innerHTML="";
              return;
            } 
          if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
          else
          {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

          xmlhttp.onreadystatechange=function()
          {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
              {
                document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText;
              }
          }

        var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(); 


 });

This question is related to javascript

The answer is


Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...

setTimeout(function () { 

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....

}, 0);

HTML : Pass the whole body inside on click

div class="calculate" id="calculate">
            <div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
        </div>

Then write the JavaScript code inside the function "myCode()"

function myCode()
{
    var bill = document.getElementById("currency").value ;

    var people_count = document.getElementById("number1").value;
    var select_value = document.getElementById("select").value;

    var calculate = document.getElementById("calculate");

    calculate.addEventListener("click" ,function()
    {
        console.log(bill);
        console.log(people_count);
        console.log(select_value);
    });
}

you will get your values I am using visual studio code editor


Easier and more succinct with || ...:

$(document).ready(function(){


  var str = ((document.getElementById("cal_preview")||{}).value)||"";
  var str1 = ((document.getElementById("year")||{}).value)||"";
  var str2 = ((document.getElementById("holiday")||{}).value)||"";
  var str3 = ((document.getElementById("cal_option")||{}).value)||"";


    if (str=="" && str1=="" && str2=="" && str3=="" )
      {
        document.getElementById("calendar_preview").innerHTML="";
          return;
        } 
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.onreadystatechange=function()
      {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText;
          }
      }

    var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(); 


});

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)


add "MainContent_" to ID value!

Example: (Error)

document.getElementById("Password").value = text;

(ok!)

document.getElementById("**MainContent_**Password").value = text;

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

<input type="text" id="first_name" name="first_name">

or

<input type="text" id="student_first_name" name="student_first_name">

Then you try make a call like this below in your JavaScript code

var first_name = document.getElementById("first_name").value;

or

var student_first_name = document.getElementById("student_first_name").value;

You are certainly going to have an error like Uncaught TypeError: Cannot read property 'value' of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

HTML

<input type="text" id="firstname" name="firstname">

or

<input type="text" id="studentfirstname" name="studentfirstname">

Javascript

var firstname = document.getElementById("firstname").value;

or

var studentfirstname = document.getElementById("studentfirstname").value;

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Hope this helps someone stop pulling their hair like I was.


Add a check

if (document.getElementById('cal_preview') != null) {
    str = document.getElementById("cal_preview").value;
}