I’ve been trying to make a web-based tallying-application using javascript. I got it to work, but only for the first instance of a class (e.g. first tallying-element).
How do I make the function work for multiple the subsequent instances of the tallying-elements?
Also, I’m using Bootstrap v5.1.3 for the css, but did not add the lengthy code.
Your help is greatly appreciated!
let add = document.querySelector(".add");
let minus = document.querySelector(".minus");
let reset = document.querySelector(".reset");
let counter = document.querySelector(".counter");
add.addEventListener('click', addCounter);
minus.addEventListener('click', minusCounter);
reset.addEventListener('click', resetCounter);
function addCounter(item) {
counter_num = counter.innerHTML
counter.innerHTML = parseInt(counter_num) + 1
}
function minusCounter(){
counter_num = counter.innerHTML
if (counter_num == 0){
return false
}
counter.innerHTML = parseInt(counter_num) - 1
}
function resetCounter(){
if (counter.innerHTML == 0){
return false
}
if (confirm("Weet je zeker dat je de telling wilt resetten?") == true){
counter.innerHTML = 0;
resetCounter = "De telling is gereset!"
} else {}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=devide-width", initial-scale="1.0">
<link rel="stylesheet" href="bootstrap.min.css">
<title>Turf-app geadresseerd voorschrijven</title>
<style>
.counter{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}
.tally_container{background-color:lightgrey; border-radius: 10px; padding:20px;}
.add{width: 38px; height: 38px;}
.minus{width: 38px; height: 38px;}
.title-text{color: white;}
.counter2{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}
</style>
</head>
<body class="jumbotron bg-dark">
<h1 class="text-center mx-4 mt-4 mb-5 title-text">Turf-app geadresseerd voorschrijven</h1>
<div class="container" id="1">
<div class="tally_container mt-3 mb-3" name="tally-element">
<div class="vraag-container mb-3">
<h3>Patiƫnten zonder recept</h3>
</div>
<div class="counter-div text-center">
<div class="mx-2 text-center mb-2 counter bg-dark">0</div>
</div>
<div class="buttons">
<button class="btn btn-success mx-2 add">+</button>
<button class="btn btn-danger mx-2 minus">-</button> <br>
<button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
</div>
</div>
</div>
<div class="container" id="2">
<div class="tally_container mt-3 mb-3" name="tally-element">
<div class="vraag-container mb-3">
<h3>No-shows</h3>
</div>
<div class="counter-div text-center">
<div class="mx-2 text-center mb-2 counter bg-dark">0</div>
</div>
<div class="buttons">
<button class="btn btn-success mx-2 add">+</button>
<button class="btn btn-danger mx-2 minus">-</button> <br>
<button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>