Toggle Div Visibility with Span Value Change

In my quiz, there is a span that displays the sum of checked checkboxes. Depending on the value in the span, I want to show or hide two different divs. Currently, my code hides the divs but does not show them. Please help!

<div class="results center">
    Your Score Is: <span class="yes_results">0</span> 
</div>
<div id="less">less div</div>
<div id="more">more div</div> 

The span value, representing the score, is calculated using the following code:

$(document).ready(function() {
    $('.yes').change(function(){
        var yes = $('.yes:checked').length;
        var no = $('.no:checked').length;
        $('.yes_results').text(yes);
        $('.no_results').text(no);                     
    })
});

Here is the code that successfully hides the divs but does not show them:

$(function() {
    var x = $("span.yes_results").text();

    if (x == 0){
         $("div#less").hide();
         $("div#more").hide();
    }
    else if ((x > 0) && (x < 4)) {
         $("div#less").show(); 
         $("div#more").hide();
    }
    else if (x > 3) {
         $("div#less").hide(); 
         $("div#more").show();
    };
});

Answer №1

After reviewing the comments, it appears that your show/hide function is set to execute only once the document is ready, resulting in the function not running again. To address this, the function needs to be connected to the event that triggers whenever the span's value changes.

In addition, you are comparing the string output of the .text() method return value with a number, necessitating a conversion.

A more effective approach would be to integrate the functions as follows:

$(function() {
    $('.yes').change(function(){
        var yes = $('.yes:checked').length
        var no = $('.no:checked').length 
        $('.yes_results').text(yes)
        $('.no_results').text(no) 
        showHide();  // Update the display based on the span                     
    });

    showHide();  // Update the display based on the span

});


function showHide(){

    // Convert the string returned by the text() method to a number for numeric comparison
    var x = parseInt($("span.yes_results").text(),10);

    if (x == 0){
         $("div#less").hide();
         $("div#more").hide();
     } else if ((x > 0) && (x < 4)) {
         $("div#less").show(); 
         $("div#more").hide();
     } else if (x > 3) {
         $("div#less").hide(); 
         $("div#more").show();
     };

}

Answer №2

To convert the string value to an integer, modify the code below:

let result = parseInt($("span.yes_results").text());

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

Error in MongoDB Connection: Timeout issue caused by an unresolved Promise

Issue Overview Whenever I attempt to execute nodemon server, a timeout error is displayed indicating [nodemon] app crashed - waiting for file changes before starting.... Detailed Problem Description I have three files located at the following paths: ...

Combining the Powers of Angular JS and Symfony2

Currently working on a project involving Symfony2 and in need of some advice. Considering a hybrid application approach in two ways: a) Using a traditional form with CSRF Token for the Login Page handled by Symfony2, and b) Inner pages (potentially module ...

Guide on implementing vuechartkick in a Nuxt.js project

In the directory /plugin/vue-chartkick, I created a vuechartkick plugin. import Vue from 'vue' import Chartkick from 'vue-chartkick' import Chart from 'chart.js' Vue.use(Chartkick.use(Chart)) This is the nuxt template sectio ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Accessing the name attribute of the TextField component, displayed as a Select Box in Material-UI, by utilizing the event object received from the onFocus prop

Utilizing the "@material-ui/core": "4.11.2" library along with "react": "16.8.6", I've encountered an issue with the TextField component where the select prop is set to true. Specifically, I am unable to access ...

Having difficulty in executing the node app.js script

I am currently learning node.js and encountering an issue when trying to run the app.js file using the command node app.js. The terminal shows no output, neither errors nor any other information. Here is the sequence of steps I have followed: $ brew insta ...

Having trouble with CSS when using jQuery's gt() selector?

While working with jQuery, I encountered a warning from Firefox regarding the following code snippet: $("li.example div.code:gt(4)").hide(); Firefox indicates a CSS Error: Unknown pseudo-class or pseudo-element 'gt'. Although the code works as ...

Using JavaScript to interact with text elements in external SVG documents

When it comes to creating an SVG within HTML and assigning specific IDs to text elements for easy access, everything works smoothly. For example, I can easily retrieve the ID using: let callQSO = document.getElementById("QSOcall").value; and th ...

When individuals discuss constructing a stack, or a full stack, in JavaScript, what exactly are they referring to and how does this concept connect with Node JS?

I recently started learning about node.js, but I'm struggling to understand its purpose. I have experience with JavaScript/jQuery and Angular, so I don't see how Node can benefit me. People keep talking about full stack JavaScript but I'm st ...

What is the best way to trigger card opening - through clicking or hovering?

Once the Set tag/status button on the left is clicked, I aim to display a card similar to this one on the right side. What would be the best approach to achieve this in React? Should I use regular CSS, Material UI, or React-bootstrap? https://i.stack.img ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Is there a way to retrieve the default ObjectId generated by MongoDB when using NextAuth?

Is it possible to access the MongoDB ObjectId of the user currently logged in when using Next Auth with services like Twitter? When signing in, Next Auth creates a new user, account, and session, but I'm unable to retrieve the _id value for my server ...

Guide to importing Bootstrap 5 bundle js using npm

Having some issues with implementing Bootstrap5 and NPM. The website design is using bootstrap, which works fine, but not all the JavaScript components (dropdowns, modals, etc). I want to figure out how to import the Bootstrap JS bundle without relying on ...

Delaying the activation of the code until the image upload is complete

I'm having trouble synchronizing code to upload an image using a vue composable, wait for the upload to finish, and then store the Firebase storage URL into a database. Despite getting the URL, the success code fires before the upload is complete. My ...

Quickest method for removing a series of elements

I am faced with a challenge involving a list of div elements. Once this list exceeds 100 items, I need to retain only the last 100 items and get rid of all the items that come before them. The catch is, I am trying to avoid calling the jQuery "remove" meth ...

What is the recommended approach for conducting backend validation?

As I develop a CRUD application using express.js and node.js, here is the backend API code that I have written: app.post("/signup", (req, res) => { const { name, email, password } = req.body; if (!name) { res.status(401).json("Please provide a n ...

Content Remains Visible in Inspector Despite Display Being Set to None

I've got a WordPress site set up currently where I want to hide the header and footer while still loading them. I attempted using CSS to hide them by setting their display to none, but they continue to show up on the website. Is there a proper way to ...

What is the proper method for filling a custom shape that has been created in Canvas?

I am attempting to create a custom shape, but I am facing an issue where using moveTo prevents me from filling it. Is there any method to determine points on the screen to fill a shape? Or should I use or draw another real shape in the same layer block? T ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

How to pass a JSON object to a component's constructor in Angular 2

In a unique situation, my primary component config.editor.component performs extensive processing and generates various JSON objects. I am content with this approach. The template for this component then proceeds to render another component - api.entry.com ...