Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal:

<script>
    $(document).ready(function () {
        $(".total").click(function () {
            $("#piechart").removeClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".squat").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").removeClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".benchpress").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").removeClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".deadlift").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").removeClass('hidden');
        });
    });
</script>

And here are the corresponding div elements:

<div id="piechart" class="repPieChart"></div>                
<div id="piechartS" class="repPieChart hidden"></div>
<div id="piechartB" class="repPieChart hidden"></div>
<div id="piechartD" class="repPieChart hidden"></div>

CSS Styling:

.hidden {
    display: none;
}
.repPieChart {
    width: 100%;
    height: 500px;
    border-bottom: 5px solid #898989;
}

The intention is for the first div to be visible by default without the hidden class while the others remain hidden. When clicking on an anchor tag associated with these click events, the script should toggle the visibility of the corresponding div elements. However, despite the classes being added/removed correctly based on inspection in Chrome, only the first div remains visible, triggering an error.

What could potentially be causing this issue?

Answer №1

Check out my JSFiddle to see some code in action:


$(document).ready(function () {
    var elements = ['#chartA', '#chartB', '#chartC', '#chartD'];
    
    hideAll();
    
    function showElement(item) {
        for(var i = 0; i < elements.length; i++) {
            if(elements[i] === item) {
                $(elements[i]).show();
            } else {
                $(elements[i]).hide();
            }
        }
    }
    
    $(".buttonA").click(function() {
        showElement("#chartA");
    });
    
    $(".buttonB").click(function() {
        showElement("#chartB");   
    });
    
    $(".buttonC").click(function() {
        showElement("#chartC");
    });
    
    $(".buttonD").click(function() {
        showElement("");
    });
});

Updated to work properly and start hidden

Answer №2

Here's a functional example of your post – what appears to be malfunctioning?

$(document).ready(function () {
        $(".total").click(function () {
            $("#piechart").removeClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".squat").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").removeClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".benchpress").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").removeClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".deadlift").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").removeClass('hidden');
        });
    });
.hidden {
  display: none;
}
button {
  cursor: pointer;
}
#piechart {
  border: 1px dotted blue;
}
#piechartS {
  border: 1px dotted red;
}
#piechartB {
  border: 1px dotted green;
}
#piechartD {
  border: 1px dotted black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="piechart" class="repPieChart">A</div>                
<div id="piechartS" class="repPieChart hidden">S</div>
<div id="piechartB" class="repPieChart hidden">B</div>
<div id="piechartD" class="repPieChart hidden">D</div>

<button class="total">
Total!
</button>
<button class="squat">
Squat!
</button>
<button class="benchpress">
Benchpress!
</button>
<button class="deadlift">
Deadlift!
</button>

However, there is a way to make this much shorter. Below, each button now has a data-for attribute that corresponds to a specific div. This code snippet simply shows the relevant div and hides all its siblings:

$(document).ready(function() {
      $(".holdLiftMenuLI a").on("click", function() {
        $("#" + $(this).data("for")).removeClass("hidden")
          .siblings().addClass("hidden");
      });
    });
.hidden {
  display: none;
}
.holdLiftMenuLI {
  list-style-type: none;
}
.holdLiftMenuLI a {
  cursor: pointer;
}
#piechart {
  border: 2px solid blue;
}
#piechartS {
  border: 2px solid red;
}
#piechartB {
  border: 2px solid green;
}
#piechartD {
  border: 2px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="piechart" class="repPieChart">A</div>
  <div id="piechartS" class="repPieChart hidden">S</div>
  <div id="piechartB" class="repPieChart hidden">B</div>
  <div id="piechartD" class="repPieChart hidden">D</div>
</div>

<div class="holdLiftMenu">
  <ul class="holdLiftMenuUL">
    <li class="holdLiftMenuLI"><a class="holdLiftMenuA total current" data-for="piechart">Total</a></li>
    <li class="holdLiftMenuLI"><a class="holdLiftMenuA squat" data-for="piechartS">Squat</a></li>
    <li class="holdLiftMenuLI"><a class="holdLiftMenuA benchpress" data-for="piechartB">Benchpress</a></li>
    <li class="holdLiftMenuLI"><a class="holdLiftMenuA deadlift" data-for="piechartD">Deadlift</a></li>
  </ul>
</div>

By changing the selectors in jQuery to target the li’s and a’s, everything continues to function smoothly.

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

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

Tips for accessing the names of subdirectories and files on a website

If we have the URL, is it possible to access the names of the files within the parent directory? Similar to how we can do in DOS by using the command "DIR" to view the list of files inside a folder. For example, if we have a URL like , I am curious to kno ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Deactivate filtering for the column in the header, while retaining it in the toolbar

I am currently working on implementing a jqGrid table. https://i.stack.imgur.com/d80M8.png My goal is to disable the filter functionality from the header column, while keeping it in the filter toolbar. Is there a way to deactivate the ui-search-input fo ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

Performing jQuery Ajax Request with multiple Form Elements

I have created multiple forms using my php code, as demonstrated below. My issue is that when I try to make a jquery-ajax request, I'm not sure how to reference a specific form. My objective is for the relevant form data to be posted when the submit ...

Acquiring variables from a JQuery Ajax request while invoking a JavaScript file

I'm currently experimenting with using JQuery Ajax to retrieve a javascript file. I need to pass some parameters to it, but I'm not entirely sure how to do so in Javascript (PHP seems easier for this). Here is my current setup: function getDocum ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Template does not reflect changes made to filters in real-time

I've been working on filtering my "PriceList" collection and sorting is functioning perfectly. However, I'm experiencing some issues with implementing filters and search functionality. When I click on custom filter buttons, the template doesn&apo ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

Creating Dynamic Tables with jQuery

I have written a code to fetch values using jQuery and Ajax. The data is coming fine but I am facing an issue with populating the rows in my table. The loop doesn't seem to work properly. Here is my HTML table code: <div class="panel-body"> ...

I am experiencing issues with my local MongoDB database not properly storing data when using Express and Mongoose

I am encountering an issue where my code is functioning correctly in the console but it is not saving data to the database. Every time I restart the server, the data gets reset. While I can read data from the database without any problem, the issue arise ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...

Encountering repetitive actions during the processing of the MVC controller operation

Currently, I'm making an ajax request to my controller for processing. However, when I look at the message in my ajax done function, it displays two outcomes. The output from console.log is: {"result_code":1,"result_message":"Contact tags deleted"," ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...