How to hide the legend display for a specific chart? - javascript
What I'm trying now is if I have 1 chart and then, when I click on a button with the "onchange" function, it'll display several chart. But when I'm clicking back, I have the chart I want but there is still the "legend" of the 2nd chart in the top of the 1st chart.
Is there a way to remove it ? I've found options: { legend: { display: false } but it remove the legend for all the chart.
Here is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {}
});
function toggleCategories(e){
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
}
chart.update();
}
</script>
</body>
</html>
Cordially
Chart.js highly depends on its data. Therefore, the easiest way is just dynamically populating the necessary data to your chart whenever you need it. This should add and remove the legend as expected. However, don't forget updating your chart on data change.
Let's add some code to get an idea about it, since basically you're actually doing it - but just a little bit wrong.
The data of your chart is stored in dataset. As we can see you have 2 entries whereas the 2nd one is just an object containing a boolean property (fill). Therefore, it's displaying undefined in your legend at the very beginning.
datasets: [{
label: 'My test1',
fill: false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {
fill: false
}]
However, when toggling the the checkbox it looks fine, since you're overwriting everything within your toggleCategories as seen below.
function toggleCategories(e) {
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
...
}
chart.update();
}
But taking a closer look to else shows what's going on here.
// Those 3 lines just reset on index 1, it doesn't get deleted
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
So in order to get rid of the 2nd legend when you only want 1, you simply have to remove the object of dataset[1] and re-add it whenever you need it.
You might want to look into this fiddle for a fully working example:
It could be a solution?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div>
<h5 id="legend" style="text-align: center;">My test 1</h5>
</div>
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {legend:{display: false}}
});
function toggleCategories(e){
if (e.target.checked) {
changeLegendOnCl();
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
document.getElementById("legend").innerHTML = "My test 1";
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test1';
chart.data.datasets[1].data = test1;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
}
chart.update();
}
function changeLegendOnCl(){
document.getElementById("legend").innerHTML = "My test 2"+" "+"My test 3";
}
</script>
</body>
</html>
Related
How to use ChartjsPluginStacked100 javascript only, no typescript
good day. Im trying to use the plugin chartjs-plugin-stacked100 with chart.js vs3 but im not having any luck. it stays as normal stacked horizontal bar chart. I think im doing something wrong when importing or registering i but not know what im doing wrong. here is how im doing my html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-stacked100#1.0.0"></script> </head> <body> <div id="my-chart-container" style="height:400px;"> <canvas id="my-chart" ></canvas> </div> <script src="./index.js" type="module"></script> </body> </html> and here is how im doing my js: Chart.register(ChartjsPluginStacked100); new Chart(document.getElementById("my-chart"), { type: "bar", data: { labels: ["2010-2015", "2016", "2017", "2018", "2019"], datasets: [ { label: "IG", data: [0, 250, 7417.5, 650, 1455], backgroundColor: "rgba(244, 143, 177, 0.6)" }, { label: "HY", data: [0, 0, 0, 1000, 0], backgroundColor: "rgba(255, 235, 59, 0.6)" }, { label: "NR", data: [0, 675, 4182.5, 1505, 1735], backgroundColor: "rgba(100, 181, 246, 0.6)" } ] }, options: { indexAxis: 'y', scales: { xAxis:{ stacked:true }, yAxis:{ stacked:true }, }, tooltips: { callbacks: { label: (tooltipItem, data) => { const datasetIndex = tooltipItem.datasetIndex; const datasetLabel = data.datasets[datasetIndex].label; // You can use two type values. // `data.originalData` is raw values, // `data.calculatedData` is percentage values, e.g. 20.5 (The total value is 100.0) const originalValue = data.originalData[datasetIndex][tooltipItem.index]; const rateValue = data.calculatedData[datasetIndex][tooltipItem.index]; return `${datasetLabel}: ${rateValue}% (raw ${originalValue})`; } } }, plugins: { plugins:[ChartDataLabels], stacked100: { enable: true, replaceTooltipLabel: false } } } }); if anyone can guide me to do it correctly would be appreciated. here is a jsbin with it, example Thanks for your time.
interactive Button doesn't hide the chart as I intended
I'm trying to link a set of data to each green button up in the display: I'd like to click the button and display half of the curves in my graph. I created the buttons, the function and linked data but it doesn't work. The end goal is to click the button (a month) and display just a portion of the three curves: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <title>Covid Piemonte 2020</title> <h1>Evoluzione del virus Covid-19 nel bimestre marzo-aprile 2020 (Piemonte)</h1> <br> <button class="btn btn-success" onclick="updateChart()">MARZO</button> <button class="btn btn-success" onclick="updateChart1()">APRILE</button> <br> </head> <body> <div class="container"> <canvas id="myChart" width="720" height="360"></canvas> </div> <script> var label1 = ['16-marzo', '17-marzo', '18-marzo', '19-marzo', '20-marzo', '21-marzo', '22-marzo', '23-marzo', '24-marzo', '25-marzo', '26-marzo', '27-marzo', '28-marzo', '29-marzo', '30-marzo', '31-marzo', '1-aprile', '2-aprile', '3-aprile', '4-aprile', '5-aprile', '6-aprile', '7-aprile', '8-aprile', '9-aprile', '10-aprile', '11-aprile', '12-aprile', '13-aprile', '14-aprile', '15-aprile', '16-aprile', '17-aprile', '18-aprile', '19-aprile', '20-aprile', '21-aprile', '22-aprile', '23-aprile', '24-aprile', '25-aprile', '26-aprile', '27-aprile', '28-aprile', '29-aprile', '30-aprile']; var olddata = [5589, 6872, 8140, 9424, 10590, 11799, 12869, 14619, 16110, 17509, 18486, 20197, 22829, 24782, 26578, 28918, 31135, 33431, 36547, 38638, 40638, 43306, 46927, 51311, 55548, 60271, 65391, 69003, 71615, 74060, 78066, 83130, 89136, 94278, 99008, 102082, 107850, 113930, 120387, 127108, 132510, 137069, 140996, 146173, 152447, 158762, 164053, 170109]; var olddata1= [1516, 2063, 2659, 3017, 3576, 4059, 4541, 5094, 5767, 6193, 6708, 7228, 7920, 8461, 8835, 9418, 9918, 10466, 11082, 11839, 12442, 13046, 13434, 13964, 14671, 15412, 16109, 16733, 17246, 17773, 18446, 19261, 19954, 20581, 21144, 21437, 22149, 22854, 23319, 24050, 24549, 24910, 25216, 25538, 25995, 26453]; var olddata2= [111, 144, 166, 183, 224, 255, 300, 336, 403, 483, 545, 598, 662, 734, 795, 854, 924, 1018, 1088, 1144, 1191, 1284, 1349, 1349, 1417, 1487, 1591, 1689, 1788, 1876, 1969, 2064, 2146, 2224, 2302, 2379, 2453, 2524, 2598, 2668, 2737, 2803, 2859, 2913, 2966, 3032, 3086]; let myChart = (document.getElementById('myChart').getContext('2d')); let myCovidChart = new Chart(myChart, { type: 'line', data:{ labels:label1, datasets:[{ data:olddata, label: 'numero cumulativo dei Tamponi', borderColor:'green', },{ data:olddata1, label: 'Numero incrementale dei contagiati', borderColor: 'red', },{ data: olddata2, label: 'Numero incrementale dei decessi', borderColor: 'blue', }] }, options:{ } }); function updateChart(){ { function updateChart(){ chart.data.datasets[0].data = [74060, 78066, 83130, 89136, 94278, 99008, 102082, 107850, 113930, 120387, 127108, 132510, 137069, 140996, 146173, 152447, 158762, 164053, 170109]; chart.update(); } } }; </script> </body> </html>
I think I see two issues with your current code. Your chart variable is myCovidChart, but in updateChart you reference chart. Your function updateChart defines a local function also called updateChart, but doesn't call it. These can be fixed by changing the updateChart function to: function updateChart() { myCovidChart.data.datasets[0].data = [120387, 127108, 132510, 137069, 140996, 146173, 152447, 158762, 164053, 170109]; myCovidChart.update(); }
As domdomegg pointed out in his answer your update function was not correct, the chart pointed to the wrong variable because chart was nothing because you stored the chart in the myCovidChart, also the update function didnt work because you nested it double with a lot of extra brackets so it couldnt find the variable anymore. If you remove all extra clutter and point to the right variable it will work Example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <title>Covid Piemonte 2020</title> <h1>Evoluzione del virus Covid-19 nel bimestre marzo-aprile 2020 (Piemonte)</h1> <br> <button class="btn btn-success" onclick="updateChart()">MARZO</button> <button class="btn btn-success" onclick="updateChart1()">APRILE</button> <br> </head> <body> <div class="container"> <canvas id="myChart" width="720" height="360"></canvas> </div> <script> var label1 = ['16-marzo', '17-marzo', '18-marzo', '19-marzo', '20-marzo', '21-marzo', '22-marzo', '23-marzo', '24-marzo', '25-marzo', '26-marzo', '27-marzo', '28-marzo', '29-marzo', '30-marzo', '31-marzo', '1-aprile', '2-aprile', '3-aprile', '4-aprile', '5-aprile', '6-aprile', '7-aprile', '8-aprile', '9-aprile', '10-aprile', '11-aprile', '12-aprile', '13-aprile', '14-aprile', '15-aprile', '16-aprile', '17-aprile', '18-aprile', '19-aprile', '20-aprile', '21-aprile', '22-aprile', '23-aprile', '24-aprile', '25-aprile', '26-aprile', '27-aprile', '28-aprile', '29-aprile', '30-aprile']; var olddata = [5589, 6872, 8140, 9424, 10590, 11799, 12869, 14619, 16110, 17509, 18486, 20197, 22829, 24782, 26578, 28918, 31135, 33431, 36547, 38638, 40638, 43306, 46927, 51311, 55548, 60271, 65391, 69003, 71615, 74060, 78066, 83130, 89136, 94278, 99008, 102082, 107850, 113930, 120387, 127108, 132510, 137069, 140996, 146173, 152447, 158762, 164053, 170109]; var olddata1 = [1516, 2063, 2659, 3017, 3576, 4059, 4541, 5094, 5767, 6193, 6708, 7228, 7920, 8461, 8835, 9418, 9918, 10466, 11082, 11839, 12442, 13046, 13434, 13964, 14671, 15412, 16109, 16733, 17246, 17773, 18446, 19261, 19954, 20581, 21144, 21437, 22149, 22854, 23319, 24050, 24549, 24910, 25216, 25538, 25995, 26453]; var olddata2 = [111, 144, 166, 183, 224, 255, 300, 336, 403, 483, 545, 598, 662, 734, 795, 854, 924, 1018, 1088, 1144, 1191, 1284, 1349, 1349, 1417, 1487, 1591, 1689, 1788, 1876, 1969, 2064, 2146, 2224, 2302, 2379, 2453, 2524, 2598, 2668, 2737, 2803, 2859, 2913, 2966, 3032, 3086]; let myChart = (document.getElementById('myChart').getContext('2d')); let myCovidChart = new Chart(myChart, { type: 'line', data: { labels: label1, datasets: [{ data: olddata, label: 'numero cumulativo dei Tamponi', borderColor: 'green', }, { data: olddata1, label: 'Numero incrementale dei contagiati', borderColor: 'red', }, { data: olddata2, label: 'Numero incrementale dei decessi', borderColor: 'blue', }] }, options: { } }); function updateChart() { myCovidChart.data.datasets[0].data = [74060, 78066, 83130, 89136, 94278, 99008, 102082, 107850, 113930, 120387, 127108, 132510, 137069, 140996, 146173, 152447, 158762, 164053, 170109]; myCovidChart.update(); }; </script> </body> </html>
Chart.js - How to update data
I've created chart that shows temperature from past 20 minute. Data is obtained via GET request from my Thingspeak meteo station. How could I send new request every 10 seconds and update only data in chart. I think chart.update() would work, but I have no idea how to implement it :/ Here is some code: chartIt(); async function chartIt(){ const loadedData = await loadData(); var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), { type: 'line', backgroundColor: 'rgba(255, 251, 230, 0.5)', data: { labels: loadedData.timeStamp, datasets: [{ label: 'Temperature', data: loadedData.chartData, backgroundColor: [ 'rgba(255, 0, 132, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)' ], borderWidth: 1 }] }, }) } async function loadData() { var chartData = []; var timeStamp = []; await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) { $.each(data.feeds, function(){ var value = this.field1; var raw_time = this.created_at; if (value) { value = (value / 1000) * 1000; value = parseFloat(value.toFixed(2)); } if (raw_time){ var timewZ = raw_time.split("T").slice(1); } chartData.push(value); timeStamp.push(timewZ); }); }); return {chartData, timeStamp}; } .chartWrapper{ width: 500px; height: 500px; margin:auto; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="chartWrapper"> <canvas id="tempChart"></canvas> </div> </body> <script src="script.js"></script> </html>
This is simplistic but would do the trick. If you wanted to enable/disable it, you'd want to hang onto your interval so you can kill it... This works though! :) const updateFreqency = 10000; chartIt(updateFreqency); async function chartIt(interval){ const loadedData = await loadData(); var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), { type: 'line', backgroundColor: 'rgba(255, 251, 230, 0.5)', data: { labels: loadedData.timeStamp, datasets: [{ label: 'Temperature', data: loadedData.chartData, backgroundColor: [ 'rgba(255, 0, 132, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)' ], borderWidth: 1 }] }, }) setInterval(async () => { const data = await loadData(); myChart.data.datasets.forEach(d => d.data = data.chartData) myChart.labels = data.timeStamp myChart.update() }, interval) } async function loadData() { var chartData = []; var timeStamp = []; await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) { $.each(data.feeds, function(){ var value = this.field1; var raw_time = this.created_at; if (value) { value = (value / 1000) * 1000; value = parseFloat(value.toFixed(2)); } if (raw_time){ var timewZ = raw_time.split("T").slice(1); } chartData.push(value); timeStamp.push(timewZ); }); }); return {chartData, timeStamp}; } .chartWrapper{ width: 500px; height: 500px; margin:auto; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="chartWrapper"> <canvas id="tempChart"></canvas> </div> </body> <script src="script.js"></script> </html>
basically you need access to chart so if you move its context/scope to be outside of the function then you can access it from another function.... something like.... ommited some of the code as well this is the core bits.. //moved out var myChart; async function chartIt(){ const loadedData = await loadData(); myChart = new Chart(document.getElementById("tempChart").getContext('2d'), { type: 'line', backgroundColor: 'rgba(255, 251, 230, 0.5)', data: { labels: loadedData.timeStamp, datasets: [{ label: 'Temperature', data: loadedData.chartData, backgroundColor: [ 'rgba(255, 0, 132, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)' ], borderWidth: 1 }] }, }) } function myTimer() { var loadedData = await loadData(); //have access here as it was move out of the function which created it. myChart.data.labels = loadedData.timeStamp; myChart.data.datasets = loadedData.chartData; myChart.update(); } var myVar = setInterval(myTimer, 10000);
Cannot display two Chart.js on one HTML page
I am trying to display more Chart.js graphics on a single HTML page, but it does not work. I tried several approaches, but none of them had a positive result. I will attach my code: #extends('layouts.app') <!DOCTYPE html> <html lang="zxx"> #section('content') <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/patternomaly#1.3.2/dist/patternomaly.min.js"></script> #php $dates = ''; $rates = ''; $graph_data = \App\Helpers\NjHelper::bettingData(); foreach ($graph_data as $item){ $dates .= "'".$item->date."',"; $rates .= $item->bankers.","; } #endphp #php $datesValue = ''; $ratesValue = ''; $graph_data_value = \App\Helpers\NjHelper::bettingDataValueBets(); foreach ($graph_data_value as $item){ $datesValue .= "'".$item->date."',"; $ratesValue .= $item->value_bet.","; } #endphp <script> $(function () { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{!! $dates !!}], datasets: [{ label: 'Bankers Profit Per Day', data: [{!! $rates !!}], borderColor: [ 'rgba(243, 156, 18, 1)', 'rgba(243, 156, 18, 1)', 'rgba(243, 156, 18, 1)' ], borderWidth: 3 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, legend: { labels: { fontSize: 20 } } } }); var ctx_2 = document.getElementById(chartValueBets).getContext('2d'); var chartValueBets = new Chart(ctx_2, { type: 'line', data: { labels: [{!! $datesValue !!}], datasets: [{ label: 'Value Bets Profit Per Day', data: [{!! $ratesValue !!}], borderColor: [ 'rgba(243, 156, 18, 1)', 'rgba(243, 156, 18, 1)', 'rgba(243, 156, 18, 1)' ], borderWidth: 3 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, legend: { labels: { fontSize: 20 } } } }); }); </script> </head> <div class="col-lg-12 col-xl-4"> <canvas id="myChart" width="400" height="400"></canvas> <canvas id="chartValueBets" width="400" height="400"></canvas> </div> #endsection </html> The data that I want to be displayed comes from some SQL queries, this is the reason why I have those two #php sections before the charts. Only the first chart appears on my HTML page, the one with the name "myChart". Does anyone know what I could do in order to make the second one appear as well?
On the following line: var ctx_2 = document.getElementById(chartValueBets).getContext('2d'); You are missing quotation marks around "chartValueBets." If you add quotation marks, it should work properly.
How to pass variables from Razor to JavaScript?
I have one C# variable "value" that I want to pass into JavaScript Chartjs data object. It renders the chart but does not include the two #p values. See code source below: cshtml file: #{ int p1 = 43; int p2 = 45; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div style="width: 400px;"> <canvas id="lineChart" width="400" height="400"></canvas> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <script src="main.js"></script> </body> </html> javascript file: var chart = document.getElementById("lineChart"); var data = { labels: [2012, 2013, 2014, 2015, 2016, 2017], datasets: [ { label: "My Chart Label", fill: false, lineTension: 0.1, data: ['(#p1)', '(#p2)', 50, 48, 47, 52] } ] }; var lineChart = new Chart(chart, { type: 'line', data: data } ); How can I write it so that it works?
You can do <script type="text/javascript"> var p1 = #p1, p2= #p2; </script> and use p1, p2. var data = { labels: [2012, 2013, 2014, 2015, 2016, 2017], datasets: [ { label: "My Chart Label", fill: false, lineTension: 0.1, data: [p1, p2, 50, 48, 47, 52] } ] }; In this case you don't have to use hidden html fields and you can expand your code to use more field like var tempObj ={ tempData: "", otherData:"", moreData: "" }
Something like below View: #{ var p1 = 43; var p2 = 45 } <input type="hidden" id="PassingToJavaScript1" value=#p1> <input type="hidden" id="PassingToJavaScript2" value=#p2> JavaScript: var p1 = document.getElementById('PassingToJavaScript1').value; var p2 = document.getElementById('PassingToJavaScript2').value;
Use a hidden field which will hold the value and then read the hidden field's value from JavaScript. Example: #{ int p = 43; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div style="width: 400px;"> <canvas id="lineChart" width="400" height="400"></canvas> <input type="hidden" id="someId" value="#p" /> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <script src="main.js"></script> </body> </html> JS var chart = document.getElementById("lineChart"); var hiddenFieldValue = document.getElementById("someId").value; var data = { labels: [2012, 2013, 2014, 2015, 2016, 2017], datasets: [ { label: "My Chart Label", fill: false, lineTension: 0.1, data: ['(hiddenFieldValue)', 45, 50, 48, 47, 52] // Not really sure how to format the data but you get main idea... } ] }; var lineChart = new Chart(chart, { type: 'line', data: data } );