Having trouble accessing the property 'length' of a null value - resolving with CSS display block on select and onchange

I have incorporated Google Charts into my project, where the charts are displayed based on a selection made from a drop-down menu:

<select id="form_frame1" name="frame1" onchange="getChart(this);">
   <option value="area_chart_google" >Area Chart</option>
   <option value="area_chart_2" selected="selected">Stacked Chart</option>
</select>

The getChart function I am using is as follows:

function getChart(selection) {
 if (selection.value == "area_chart_2") {
    document.getElementById('area_chart_2').style.display = 'block';
    document.getElementById('area_chart_google').style.display = 'none';
}

 else {   
    document.getElementById('area_chart_2').style.display = 'none';
    document.getElementById('area_chart_google').style.display = 'block';
   }
}

Everything works fine when the default display property is set to 'block' for area_chart_google. However, an error occurs when I hide and then show the chart. The error messages I receive are:

In Firebug: google-visualization-errors-all-1 
In Chrome: Cannot read property 'length' of null
In Safari: 'null' is not an object

Here is the HTML structure (with the script inside the body tag and JSAPI in the header):

<div id="area_chart_google" class="area-chart"></div>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Header');
    data.addColumn('number', '');
    data.addColumn('number', '');
    data.addRows([
      ['Monday',300,43],
      ['Tuesday',250,545],
      ['Wednesday',122,78],
      ['Thursday',348,92],
      ['Friday',23,61],
      ['Saturday',39,93]
    ]);
    var options = {
      title: '',
      hAxis: {title: '',  titleTextStyle: {color: '#efed22'}},
      backgroundColor: '#efede9',
      legend: 'none'
    };
    var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
    chart.draw(data, options);
  }
</script>

Answer №1

This solution is effective for me:

function showSelectedChart(selection) {
  if (selection.value == "area_chart_2") {
    document.getElementById('area_chart_2').style.display = 'block';
    document.getElementById('area_chart_google').style.display = 'none';
  } else {   
    document.getElementById('area_chart_2').style.display = 'none';
    document.getElementById('area_chart_google').style.display = 'block';
    drawChart(); //invoke this function when using the Google Chart
  }
}

Answer №2

Perhaps the issue arises when a dynamic script attempts to access the length property of concealed divs.

According to a helpful explanation, using display: none does not occupy space on the webpage. Consider these alternatives:

  1. Try using visibility: hidden instead
  2. Hide the parent element of area_chart_2 and area_chart_google instead

Answer №3

Since your enquiry was categorized under jQuery, I have tailored a jQuery based solution:

function retrieveData(option) {

   var $line_chart = $("#line_chart"),
       $bar_chart = $("#bar_chart");

   if (option.value === "line_chart") {
      $line_chart.show(); //Alternatively, you can also use $line_chart.css("display", "block");
      $bar_chart.hide(); //Another option is to utilize $bar_chart.css("display", "none");
   } else {   
      $line_chart.hide();
      $bar_chart.show();
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to display each element in a list one by one with a three-second interval and animated transitions in React

Let's consider a scenario where we have a component called List: import React, { Component } from 'react'; class List extends Component { constructor() { super(); this.state = { list: [1, 2, 3, 5] } ...

Easy steps to prevent window.onbeforeunload from triggering when submitting a form using Vue

Presently, I am utilizing a component named countdowntimer.vue, specifically designed as a countdown timer for an online examination platform. My goal is to implement an onbeforeunload event on the window object while ensuring that the timer automatically ...

Using CSS and jQuery to Enhance Page Transitions

Seeking assistance with creating a unique page transition similar to this one: Basing the animation on my own design concept found here: Current experiment can be viewed at: https://jsfiddle.net/f7xpe0fo/1/ The animation does not align with my design vi ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Strategies for reducing the need for multiple if/else statements when filtering result sets

Currently, my webpage has a left and right section. The right section displays results based on the filters chosen by the user on the left. Upon selecting filters and clicking a button, a query is sent to the server to retrieve the relevant results. I&apo ...

Sending an XMLHttpRequest in PHP causes a blank array to be returned

> xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var jsondata = xmlhttp.responseText; console.log(xmlhttp.responseText); document.getElementById("jsondata").value = js ...

Creating an image rollover effect when hovering between two images

I am currently working with React and trying to change 2 images by hovering over them. Here is what I have accomplished so far: Card.js <div className="image-wrapper"> <img src={sprites.front_default} className="image" a ...

Utilizing a switch to deactivate all currently active classes on individual div elements

I'm currently facing an issue with implementing a toggle feature in a particle manner. I have three divs with onclick events and each has a toggle CSS class. My goal is to ensure that when one div is clicked, if the others are active, they revert back ...

Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with: ...

Difficulty encountered when trying to customize a polymer element that has been expanded (paper-slider)

I've been customizing the Polymer paper-slider element to handle an enumerated list and cycle through these values in the slider instead of just showing numeric values. However, I'm struggling with getting the styles to align properly. When you r ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

Press the confirm button to halt the AJAX process

I encountered an issue with my code where a CONFIRM message shows up when I click on the A button. However, despite choosing CANCEL, the AJAX request still continues and deletes my record. What could be causing this unexpected behavior? <a href=' ...

Retrieve information from the API every second

In my React Native app, I have a system where customer orders are fetched and displayed on the restaurant side in a specific screen. I'm using the Fetch API to retrieve this data. The workflow is as follows: the customer places an order, which is then ...

I always love playing around with CSS to create unique effects with my images, constantly changing their size through shrinking

I'm working on coding 3 different boxes. Each box consists of an image and a title in the first column, followed by a paragraph, and a link at the bottom. The boxes themselves are not editable, only the content inside them can be changed. The challeng ...

To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far: function hidekeep() { ...

Move the cursor to a specific position within a contentEditable <div> element

I am in search of a reliable solution that works seamlessly across browsers to set the cursor/caret position to the last known location when a contentEditable='on' <div> regains focus. By default, the cursor/caret in a content editable div ...

Clear information upon clicking to switch to a new controller

I have a scenario where one div contains another div. The contained div has its own controller that controls its visibility based on a variable changed by clicking an icon button in the container. The structure is as follows: <div ng-controller="BarCo ...

Discovering indistinguishable "Feeling Fortunate" inquiries

My goal is to create a program on my website that can compare the top search results for different queries. For instance, I want it to recognize that the top search result for "twelve" and "12" is the same, leading to https://en.wikipedia.org/wiki/12_(numb ...

Checking form input using AJAX validation before submitting

I am attempting to create a data input form, but I have run into an issue. Even when the form is empty, it can still be saved when the save button is pressed. How can I prevent saving if the input fields are empty? Here is the code for my form: https://js ...

What is the best way to retrieve information from a web service using Vue.js within an HTML environment?

I'm trying to retrieve data from a web service using vue.js, but I'm having trouble fetching the data. Can I use vue.js without installing node.js? Any help would be appreciated. Thank you in advance. <!DOCTYPE html> <html lang="en> ...