I am trying to create a Google PieChart from five inputs, the first two numerical inputs are added and the result is stored in sessionStorage. The stored value is retrieved and together with the three remaining inputs are supposed to create a 4-sliced Google PieChart. The GoogleChart code works but my problem is that the sessionStorage value is not included in the piechart, only the three inputs are! Here is the code:
<body>
<p>How many hours do you spend per week?</p>
<form id="form1" onsubmit="drawChart(); return false" >
<label for="workvar">Working: </label><input type="text" id="workvar" autocomplete="off"><br>
<label for="eatvar">Eating: </label><input type="text" id="eatvar" autocomplete="off" onkeyup="calculeaza();"><br>
<label for="tvvar">Watching tv: </label><input type="text" value="35" id="tvvar"><br>
<label for="sleepvar">Sleeping: </label><input type="text" value="21" id="sleepvar"><br>
<label for="othervar">Other: </label><input type="text" value="17" id="othervar"><br>
<button type="submit" value="Submit">Submit</button>
</form>
<div id="piechart" class="chart"></div>
</body>
<script>
function calculeaza() {
var Valoarea1 = parseInt(document.getElementById('workvar').value);
var Valoarea2 = parseInt(document.getElementById('eatvar').value);
var ValoareaFinala = Valoarea1 + Valoarea2;
sessionStorage.setItem('Adunare', ValoareaFinala);
}
google.charts.load('current', {'packages':['corechart']});
function drawChart() {
var tv = parseInt(document.getElementById('tvvar').value);
var sleep = parseInt(document.getElementById('sleepvar').value);
var other = parseInt(document.getElementById('othervar').value);
const commute = parseInt(sessionStorage.getItem('Adunare').value);
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Week'],
['Commute', commute],
['Watch TV', tv],
['Sleep', sleep],
['Other', other]
]);
var options = {
title: 'Weekly Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
window.onresize = function() {
drawChart();
}
</script>
There must be something wrong with storing/retrieving data from sessionStorage but I can not figure it out. Any help would be greatly appreciated, thank you.
The problem is with how you're retrieving the value from sessionStorage
. You're using .value
on sessionStorage.getItem('Adunare')
, which is incorrect.
// Incorrect
const commute = parseInt(sessionStorage.getItem('Adunare').value);
// Correct
const commute = parseInt(sessionStorage.getItem('Adunare'));
Replace the incorrect line with the correct one, and your code should work as expected.