Paige Rose Figueira Paige Rose Figueira - 1 month ago 5
CSS Question

Show/Hide Div based on dynamic value in span

I have a span that contains a number which is the sum of the total number of checkboxes checked in a quiz. I need to hide and show 2 different divs based on the number value of that span. This is the code I have which effectively hides the divs but is not showing them. 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 score (span value) is calculated by 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)
})
});


And the code that I have that is currently hiding but not showing the divs is this

$(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

As I stated in the comments, your show/hide function is being registered as a callback function for when the document is ready (which only happens once so your function doesn't run again), but you need it to run whenever the span's value changes, so you'll need it connected to that event.

You also are comparing the string results of the .text() method return value against a number, so you need to convert that.

A simple solution would be to combine the functions:

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

    showHide();  // Now, update the display based on the span

});


function showHide(){

    // The text() method will return a string, so you need to 
    // convert it to a number to be able to compare it to a number
    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();
     };

}
Comments