Comments included to explain and walk you through code functionality.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<style>
#layout {
width: 400px;
height: 400px;
}
</style>
<body>
<button onClick="updateAppleAdd()" width=80px>Apple +</button>
<button onClick="updatePearAdd()" width=80px>Pear +</button>
<button onClick="updateBananaAdd()" width=80px>Banana +</button>
<button onClick="updateMangoAdd()" width=80px>Mango +</button>
<button onClick="updateMarsBarAdd()" width=80px>MarsBar +</button>
<br/>
<button onClick="updateAppleMinus()" width=80px>Apple -</button>
<button onClick="updatePearMinus()" width=80px>Pear -</button>
<button onClick="updateBananaMinus()" width=80px>Banana -</button>
<button onClick="updateMangoMinus()" width=80px>Mango -</button>
<button onClick="updateMarsBarMinus()" width=80px>MarsBar -</button>
<div id="highestSeller">
</div>
<div id="layout">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script>
const highestSeller = document.getElementById("highestSeller");
var ctx = document.getElementById('myChart').getContext('2d');
//create two global variables
var food = ["Apple","Pear","Banana","Mango","Mars Bar"];
var data = [2,14,5,6,8];
function updateAppleAdd(){
data[0]+=1;
myChart.update();
checkMostPopular();
}
function updateAppleMinus(){
if (data[0]>0){
data[0]-=1;
myChart.update();
checkMostPopular();
}
}
function updatePearAdd(){
data[1]+=1;
myChart.update();
checkMostPopular();
}
function updatePearMinus(){
if (data[1]>0){
data[1]-=1;
myChart.update();
checkMostPopular();
}
}
function updateBananaAdd(){
data[2]+=1;
myChart.update();
checkMostPopular();
}
function updateBananaMinus(){
if (data[2]>0){
data[2]-=1;
myChart.update();
checkMostPopular();
}
}
function updateMangoAdd(){
data[3]+=1;
myChart.update();
checkMostPopular();
}
function updateMangoMinus(){
if (data[3]>0){
data[3]-=1;
myChart.update();
checkMostPopular();
}
}
function updateMarsBarAdd(){
data[4]+=1;
myChart.update();
checkMostPopular();
}
function updateMarsBarMinus(){
if (data[4]>0){
data[4]-=1;
myChart.update();
checkMostPopular();
}
}
function checkMostPopular(){
var maxSoldPointer = 0;
console.log(maxSoldPointer);
for (i = 0; i<food.length; i++){
if (data[i]>data[maxSoldPointer]){
console.log(data[i] + " is greater than " + data[maxSoldPointer])
maxSoldPointer = i;
console.log("Point to " + maxSoldPointer);
}
}
highestSeller.innerHTML = "The highest selling food is " + food[maxSoldPointer];
console.log("Highest " + food[maxSoldPointer]) +" "+ data[maxSoldPointer];
}
var myChart = new Chart(ctx, {
type: 'bar', //pie,line
data: {
labels: food ,
datasets: [{
label: '# of Votes',
data: data,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'y-axis'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'X axis'
}
}]
}
}
});
</script>
</body>
</html>
Comments included to explain and walk you through code functionality.
<html>
<head>
<title>Table and Graph.js example 1</title>
<script src = "https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<style>
#layout {
width: 600px;
height: 600px;
}
</style>
<body>
<h2>Input data, table row addition, graphing</h2>
Lap Time:<input id="secs" type="number" required> <!--ID for 'secs', gets time value -->
<button onclick="addLap()">Add Lap</button> <!--Button runs function 'addLap()' which is scripted below -->
<p id="outputBestLap"></p>
<hr>
<table id="resultsTable" border="1" width="50%"> <!--'results-table' ID outputs dynamic table using JS, but headings are set in HTML-->
<tr>
<th>Lap</th>
<th>Seconds</th>
<th>Minutes</th>
<th>Delete</th>
</tr>
</table>
<br/>
<br/>
<div id="layout"><canvas id="myChart" width="600" height="600"></canvas></div>
<!--Include JavaScript or link to JS code that sets up variables, arrays, and objects before referencing them in chart.js -->
<script>
//Set up constant references for ID areas that are included in the HTML
//These areas will be dynamically updated
const secs = document.getElementById("secs");
const outputBestLap = document.getElementById("outputBestLap");
const resultsTable = document.getElementById("resultsTable");
var lapCount = 0; //Initialise lapCount variable
var graphLapCount = []; //Initialise graphLapCount array, stores lap number
var graphLapTime = []; //Initialise graphLapTime array, stores lap time
var laps = []; //Initialise laps array, stores objects lap number & time for data management
function addLap() { //This function executes when button is pressed
lapCount ++; //Increment lapCount variable
var s = parseInt(secs.value); //Local variable s is created from user input into 'secs' ID field
laps.push({ //Add lap and time to laps array as object
lap: lapCount,
time: s
});
//add data to table
var row = resultsTable.insertRow(-1); //Add row to end of table
row.insertCell(0).innerHTML = lapCount; //Add lapCount value to column 1 (0)
row.insertCell(1).innerHTML = s; //Add time value to column 2 (1)
row.insertCell(2).innerHTML = minutes(s); //Add minutes+seconds value to column 3 (2) using minutes function - see below
row.insertCell(3).innerHTML = "<button onclick=\"removeLap(this)\">Delete</button>"; //Add BUTTON to run removeLap function to column 4 (3)
updateGraph() //Run updateGraph function
fastTime() //Run fastTime function - TBC
}
function minutes(s){ //Minutes-seconds calculator
var mins = 0;
var secs = 0;
if (s > 60) {
mins = Math.round(s/60);
secs = s % 60;
} else {
secs = s;
}
if (secs < 10) {
return mins + ":0" + secs;
} else {
return mins + ":" + secs;
}
}
function fastTime() {
//use a loop through array, based on array length, to find fastest lap time
}
function removeLap(r){ //Remove row from a table
console.log("row" + r.parentNode.parentNode.rowIndex)
var i = r.parentNode.parentNode.rowIndex; //Local variable gets number of row being clicked using parentNode.parentNode.rowIndex
resultsTable.deleteRow(i); //Delete this specific row from table
laps.splice(i-1,1); //Delete ONE specific row object from array using 'splice' ('i-1' removes the correct value from the array index)
graphLapCount.splice(i-1,1); //Delete lapCount value from array
graphLapTime.splice(i-1,1); //Delete lapTime value from array
lapCount --; //Decrement lapCount by 1
updateTable(); //Update table by running the function below - important because it 're-indexes' the lapCount values
myChart.update(); //Update graph
fastTime(); //Find and display current fastest lap
}
//function to update first column of table with correct lap numbers by looping through and 're-indexing' to the correct values of 1,2,3 etc
function updateTable(){
numberOfLaps = laps.length;
for (i=1; i <= numberOfLaps; i++){
laps[i-1]=i;
graphLapCount[i-1]=i;
resultsTable.rows[i].cells[0].innerHTML = laps[i-1];
}
}
function updateGraph(){
graphLapCount.push(lapCount);
graphLapTime.push(parseInt(secs.value));
myChart.update();
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line', //could also be pie, or bar
data: {
labels: graphLapCount,
datasets: [{
label: 'Times',
data: graphLapTime,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'y-axis'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'x-axis'
}
}]
}
}
});
</script>
</body>
</html>
Comments included to explain and walk you through code functionality.
<html>
<head>
<meta charset="UTF-8">
<title>Graph - Dynamic Input of Data</title>
<script src = "https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<style>
#layout {
width: 500px;
height: 500px;
}
</style>
<body>
<h1>Dynamic Graphing Using Chart.js</h1>
<input id="inputNumber" type="number">
<button onclick="addValue()">Add Data</button>
<div id="layout">
<canvas id="myDynamicChart" width="450" height="450"></canvas>
</div>
<h2>Results Table</h2>
<table id="myDynamicTable" width="50%" border="2">
<tr><th>Minutes</th><th>Temperature</th><th>Remove</th></tr>
</table>
<script>
const inputNumber = document.getElementById("inputNumber");
const myDynamicChart = document.getElementById("myDynamicChart");
const myDynamicTable = document.getElementById("myDynamicTable");
// insert some pre-baked data in the form of a global array of
// objects containing multiple pieces of data that can be used
// in our tabular display of data
var results = [{
localTime:0,
localTemp:10
},{
localTime:1,
localTemp:20
},{
localTime:2,
localTemp:25
}];
// create two empty arrays to store time and temp separately
// these will be used in the tabular display of data
var time = [];
var temp = [];
// run a function that serves a dual purpose - it puts the data from results
// into the time and temp arrays
getData ("time");
getData ("temp");
// the getData function to get data from object to these two arrays
function getData(dataType) {
for (var i = 0; i < results.length; i++) {
if (dataType == "time") {
time.push(results[i].localTime);
console.log(time);
} else if (dataType = "temp") {
temp.push(results[i].localTemp)
console.log(temp);
}
}
}
// display chart data from the time and temp arrays
var chart = new Chart(myDynamicChart,{
type: 'line', // type of graph
data: {
labels: time, // x-axis labels are from the time array
datasets: [{
label: 'Temperature', // y-axis label
data: temp, // y-axis data is from the temp array
backgroundColor: ['rgba(255,99,132,0.4'], //
borderColor: ['rgba(255,99,132,1'], //
borderWidth: 5
}]
}
})
// this function adds new values to the table
function addValue() {
var t = parseInt(inputNumber.value); // places the input temp value into a local variable 't'
results.push({localTime:results.length,localTemp:t}); // pushes t into the results object, as as well increasing the time by 1
time.push(results.length); // increases the time array by 1
temp.push(t); // adds temp to the time array
// add row to data table
var row = myDynamicTable.insertRow(-1); // inserts a row to the bottom of the HTML table
row.insertCell(0).innerHTML = results.length; // adds the time to the first column
row.insertCell(1).innerHTML = t; // adds the temp to the second column
row.insertCell(2).innerHTML = "<button onclick=\"removeRow(this)\"> Remove</button>";//add value to the third column
chart.update(); // updates the chart/graph
}
function buildTable() {
for (var i = 0; i < results.length; i++){
var row = myDynamicTable.insertRow(-1);
row.insertCell(0).innerHTML = results[i].localTime;
row.insertCell(1).innerHTML = results[i].localTemp;
row.insertCell(2).innerHTML = "<button onclick=\"removeRow(this)\"> Remove</button>";
console.log(this);
}
}
//function to update first column of table with correct lap numbers by looping through and 're-indexing' to the correct values of 1,2,3 etc
function updateTable(){
length = time.length;
console.log ("Time length " +length);
for (i=1; i <= length; i++){
results[i-1].localTime=i;
console.log("Time i " + results[i-1].localTime);
time[i-1]=i;
console.log("Time i " + time[i-1]);
myDynamicTable.rows[i].cells[0].innerHTML = time[i-1];
}
}
function removeRow(r) {
var i = r.parentNode.parentNode.rowIndex;
console.log(i);
myDynamicTable.deleteRow(i);
temp.splice(i-1,1); //cutting out data from the two arrays AND the results array object
time.splice(i-1,1);
results.splice(i-1,1);
updateTable();
chart.update();
}
//this function will build our tablular display of data when the page is loaded
buildTable();
</script>
</body>
</html>
.