1👍
You’ve missed parantheses in your onclick
declarations. Your button definitions should look like this to make the fundtion to be called
<button onclick="addCar()">Ford</button>
<button onclick="addCar()">Opel</button>
<button onclick="addCar()">Toyota</button>
<button onclick="nollaa()">Nollaa</button>
By making additional changes to the addCar
function, you can specify which data set should be updated.
You just need to update the part in your HTML file, for example like this
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="width: 500px;">
<h2 style="text-align: center;">Autojen lukumäärä</h2>
<button onclick="addCar(0)">Ford</button>
<button onclick="addCar(1)">Opel</button>
<button onclick="addCar(2)">Toyota</button>
<button onclick="nollaa()">Nollaa</button>
<canvas id="viivaTaulukko" height="300" width="500"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"> </script>
<script src="autolaskuri.js"></script>
<p id="Ford"></p>
<p id="Opel"></p>
<p id="Toyota"></p>
<p id="Nollaa"></p>
<script>
function addCar(columnNumber){
barChart.data.datasets[0].data[columnNumber] += 1;
barChart.update();
}
function nollaa(){
barChart.reset();
}
</script>
</body>
</html>
I’ve found another issue wthat might affect the function responsible for reseting the chart. Once the Nollaa
button will be clicked, the diagram will be cleared, but clicking on any car will bring back the whole diagram back. So before reseting the display, you might need to clear all of your data sets
function nollaa(){
let colsCount = barChart.data.datasets[0].data.length;
for (let colNo = 0; colNo < colsCount; colNo++) {
barChart.data.datasets[0].data[colNo] = 0;
}
barChart.reset();
}
Here you can find some working example https://jsfiddle.net/bnvL0eu1/4/.
Also for the future, it will be much easier to others to help you, if your HTML/JS/CSS will be embedded through the JSFiddle (How do I include code for JSFiddle?).