How can I hide a div using an event listener on multiple checkboxes?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
This is a follow up question. See the initial question here https://www.thecodingforums.com/thr...-using-an-event-listener.974420/#post-5172233

Currently, I can display or hide the DIV with the Id of SUM using only querySelector on the first checkbox with a class of jsss. This desired result of showing or hiding the DIV reacts to only the first checkbox, I did a for loop but it doesn't work, what's the correct way to make sure that the DIV with the Id of SUM displays when at least one of the all the checkboxes are clicked and it hides when no checkbox is clicked?

Image for visualization: You owe me 0 bucks does not show. Only when at least 1
Screenshot 2022-12-23 at 02-41-07 Edit fiddle - JSFiddle - Code Playground.png
checkbox is clicked will it show, with the new sum.


HTML:
<label  for=""><input class="jsss" value="50" type="checkbox">50 Bucks of many</label><br />
<label  for=""><input class="jsss" value="20" type="checkbox">20 Bucks of many</label><br />
<label  for=""><input class="jsss" value="10" type="checkbox">10 Bucks of many</label><br />
<label  for=""><input class="jsss" value="5" type="checkbox">5 Bucks of many</label><br /><br />
<div class="summm" id="SUM">

</div>

JavaScript:
//changes I have made from the previous code
        //1. I added a class of summm to the HTML DIV with id="SUM"
        //2. I added css to show or hide the div via js
        //3. comment A1 below marks the start of my attempt to make the div show or hide via js
    
let arrayItems = new Array();
let total = 0;
function removeValue(v){
var f,k=0;
for(var i=0; i<arrayItems.length; i++){
    if(arrayItems[i]==v && !f){f=true; k=i;}

}
if(f){
arrayItems.splice(k,1);
}
}
function feedArray(){
var chbox=document.querySelectorAll('.jsss');
for(var i=0; i<chbox.length; i++){

chbox[i].onclick=function(){
if(this.checked){
 arrayItems.push(this.value)
}else{
removeValue(this.value);
}
totalSet();
}
}
}
function totalSet(){
total = 0;
for (i = 0; i < arrayItems.length; i++ ) {
    total += parseFloat(arrayItems[i]);
}
document.getElementById('SUM').innerHTML="You owe me "+total+" Bucks"
}


feedArray();
totalSet();

// I am comment A1 = show or hide sum based on if any checkbox is checked

let checkboxes = document.querySelectorAll('.jsss')
let ans = ""
for (i = 0; i < checkboxes.length; i++) {
    ans = checkboxes[i]
}

const totalHide = document.querySelector('.summm')

hideOrShowTotalFunc = () => {
    if (totalHide.classList.contains('jsss')) {
        totalHide.classList.remove('jsss')
    } else {
        totalHide.classList.add('jsss')
    }
}

ans.addEventListener('change', hideOrShowTotalFunc)

CSS:
.summm{
    display: none;
}

.summm.jsss{
    display: block;
}
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
I already wrote a solution for you by changing your totalSet function? Not good enough?
Okay. Then your way. Forget about this css bulging summ.jsss. It's completely daft in that case.
CSS
Code:
.show{display:block;}
.hide{display:none;}

Than back to js and totalSet
Code:
function totalSet(){
total = 0;
for (i = 0; i < arrayItems.length; i++ ) {
    total += parseFloat(arrayItems[i]);
}
if(total>0){
document.getElementById('SUM').className='show';
document.getElementById('SUM').innerHTML="You owe me "+total+" Bucks";}else{document.getElementById('SUM').className='hide';}
}

That's it.

What exactly should that be?
Code:
hideOrShowTotalFunc = () => {
    if (totalHide.classList.contains('jsss')) {
        totalHide.classList.remove('jsss')
    } else {
        totalHide.classList.add('jsss')
    }
}

ans.addEventListener('change', hideOrShowTotalFunc)

First of all jsss is never within SUM's classList. So would'nt be called. They are completely different Elements.

Next, why the heck you need a addEventListener in your code? Lost a bet or something? For what? Doesn't make any sense at all.

Yes, addEventListsner is a great and common method. But in your case "so far" not needed.

But if you insist in using addEventListener, than remember. That method requires a element, or object (which actually is the same, each elements are also objects). Object, not Array, not String (As your whatever "ans" is supposed to be). Object.

There is no: Well, i have some checkboxes, and i need a eventListener for all of them. NO. Each one needs it's own.

Which you actually can see by just checking the method.

object.addEventListener(event <-------- event. What event? change in that case. Change what? The object of course. Not the array of objects nor the stringobject because they don't have a change event. Does this make sense to you?
 
Last edited:
Joined
Mar 11, 2022
Messages
227
Reaction score
32
By the way
Code:
let checkboxes = document.querySelectorAll('.jsss')
let ans = "" ///<---SKIP THAT BS
for (i = 0; i < checkboxes.length; i++) {
    ans = checkboxes[i] ///<---SKIP THAT BS BUT USE
checkboxes[i].addEventListener('change', hideOrShowTotalFunc); // instead if you really feel better by using addEventListener
}

But then it's better to also get the onclick functions within your hideOrShow function.
And is would go with addEventListener('click', instead of addEventListener('change'. Try what works better for you.
 
Joined
Sep 12, 2022
Messages
39
Reaction score
0
I asked this question before a solution to it was posted in the initial post. Clearly, the codes you provided there are better than the various options here, especially in-terms of readability and maintainability.
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
I asked this question before a solution to it was posted in the initial post. Clearly, the codes you provided there are better than the various options here, especially in-terms of readability and maintainability.
I've wrote a solution for exactly that post which is gone now. So my initial though was, whole post deleted by you and repostet. But maybe it was my fault by impatient saving. I struggle with weird internet for a couple days. CIA???? :)

Yes. I love readable code. There is a lot of experts out there who are able to write a code a way than a uglyfier can't do any more compression on it. I need my codes in a way, that errors are clear. Line, error itself and so on and so on. Easy to fix.
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
My version:

HTML:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <style>
    label, [type=checkbox]{
    cursor: pointer;
    }
    #choices, #sum{
    padding: 10px;
    }
    #sum b{
    color: crimson;
    }
    </style>
  
  </head>
  <body>
    <div id="choices"> 
      <label><input value="50" type="checkbox" />50 Bucks of many</label><br />
    <label><input value="20" type="checkbox" />20 Bucks of many</label><br />
    <label><input value="10" type="checkbox" />10 Bucks of many</label><br />
    <label><input value="5" type="checkbox" />5 Bucks of many</label><br />
    </div>
    <div id="sum"></div>
   <script>
   const sum = document.querySelector('#sum');
  
   document.querySelector('#choices').addEventListener('click', function(){
   const inp = [...this.querySelectorAll('input:checked')];
   sum.innerHTML = '';
   if(!inp.length) return;
   sum.innerHTML = 'You owe me <b>' + inp.map( x => +x.value ).reduce( (a, b) => a + b ) + '</b> bucks';
   });
   </script>
  </body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top