Uncaught TypeError: Cannot read property 'value' of null

Javascript

Javascript Problem Overview


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(); 
    

 });

Javascript Solutions


Solution 1 - Javascript

I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:

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;

There is either no element with the id cal_preview, year, holiday, cal_option, or some combination.

Therefore, JavaScript is unable to read the value of something that does not exist.

EDIT:

If you want to check that the element exists first, you could use an if statement for each:

var str,
element = document.getElementById('cal_preview');
if (element != null) {
    str = element.value;
}
else {
    str = null;
}

You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.

Solution 2 - Javascript

Easier and more succinct with ||:

  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(); 

Solution 3 - Javascript

Add a check

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

Solution 4 - Javascript

My mistake was that I was keeping the Javascript file (

Solution 5 - Javascript

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);

Solution 6 - Javascript

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.

Solution 7 - Javascript

add "MainContent_" to ID value!

Example: (Error)

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

(ok!)

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

Solution 8 - Javascript

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

Solution 9 - Javascript

handle through try catch

    try {
      Block of code to try
    }
    catch(err) {
      Block of code to handle errors
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2901740View Question on Stackoverflow
Solution 1 - JavascriptAnonymousView Answer on Stackoverflow
Solution 2 - JavascriptAndrew TempletonView Answer on Stackoverflow
Solution 3 - JavascriptNjaneView Answer on Stackoverflow
Solution 4 - JavascriptShachiView Answer on Stackoverflow
Solution 5 - JavascriptDavid CastroView Answer on Stackoverflow
Solution 6 - JavascriptJosephView Answer on Stackoverflow
Solution 7 - JavascriptlanshareView Answer on Stackoverflow
Solution 8 - JavascriptAvik ChandaView Answer on Stackoverflow
Solution 9 - JavascriptAli RazaView Answer on Stackoverflow