I am building a prototype that uses High charts - Data defined in a HTML table, I have applied an editable feature using jQuery so that the cells can be edited by the user. The question is:
How do I get the chart to update/refresh after a user edits a cell without using a database? I would like to use a button with an .click event listener to reload the chart from the edited table.
This is just a prototype so I have no need for an actual Ajax call or database connection. Basically I need user interaction with the table to reflect in the chart.
Here is a very simplified version:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$(function () {
$('#container').highcharts({
data: {
table: document.getElementById('datatable')
},
chart: {
type: 'column'
},
title: {
text: 'Data extracted from a HTML table in the page'
},
yAxis: {
allowDecimals: false,
title: {
text: 'Units'
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.y +' '+ this.x.toLowerCase();
}
},
});
});
$("#refresh").click(function() {
var options = chart.options;
chart = new Highcharts.Chart(options);
});
</script>
<script>
$(function () {
$("#datatable td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" +"' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td>9</td>
<td>4</td>
</tr>
<tr>
<th>Pears</th>
<td>2</td>
<td>0</td>
</tr>
<tr>
<th>Plums</th>
<td>5</td>
<td>11</td>
</tr>
<tr>
<th>Bananas</th>
<td>1</td>
<td>1</td>
</tr>
<tr>
<th>Oranges</th>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
<button id="refresh">Refresh</button>
The issue is that you were not defining your chart in:
Try defining it before you call the new HighCharts code:
See example here.
Also note you have some invalid syntax in the tooltip as well as some dangling commas.
wergeld is correct.
You may try this fiddle which just updates the series data and refreshes the chart afterwards.
This will not recreate the chart from scratch, but rather only update it.
It's a bit more code, but depending on your usecase this might be useful.
here is the code in question: