Synchronize StockChart Inputfields with external Input-Fields | CanvasJS StockCharts
Synchronize StockChart Inputfields with external HTML Input-Fields
by canvasjs
HTML
<script src="https://cdn.canvasjs.com/canvasjs.stock.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the StockChart -->
From: <input type="text" class="datepicker" id="fromDate"> To: <input type="text" class="datepicker" id="toDate">
<div id="stockChartContainer" style="height: 450px; width: 100%;"></div>
JavaScript
var dataPoints = [
{ x: new Date(2018, 0, 0), y: 71 },
{ x: new Date(2018, 01, 0), y: 55 },
{ x: new Date(2018, 02, 0), y: 50 },
{ x: new Date(2018, 03, 0), y: 65 },
{ x: new Date(2018, 04, 0), y: 95 },
{ x: new Date(2018, 05, 0), y: 68 },
{ x: new Date(2018, 06, 0), y: 28 },
{ x: new Date(2018, 07, 0), y: 34 },
{ x: new Date(2018, 08, 0), y: 14 },
{ x: new Date(2018, 09, 0), y: 71 },
{ x: new Date(2018, 10, 0), y: 55 },
{ x: new Date(2018, 11, 0), y: 50 },
{ x: new Date(2019, 0, 0), y: 71 },
{ x: new Date(2019, 01, 0), y: 55 },
{ x: new Date(2019, 02, 0), y: 50 },
{ x: new Date(2019, 03, 0), y: 65 },
{ x: new Date(2019, 04, 0), y: 95 },
{ x: new Date(2019, 05, 0), y: 68 },
{ x: new Date(2019, 06, 0), y: 28 },
{ x: new Date(2019, 07, 0), y: 34 },
{ x: new Date(2019, 08, 0), y: 14 },
{ x: new Date(2019, 09, 0), y: 71 },
{ x: new Date(2019, 10, 0), y: 55 },
{ x: new Date(2019, 11, 0), y: 50 }
];
var stockChart = new CanvasJS.StockChart("stockChartContainer", {
title:{
text: "StockChart"
},
rangeChanged: function(e) {
$("#fromDate").val(CanvasJS.formatDate(e.minimum, "YYYY-MM-DD"));
$("#toDate").val(CanvasJS.formatDate(e.maximum, "YYYY-MM-DD"));
},
charts: [{
data: [{
type: "line",
dataPoints: dataPoints
}]
}]
});
stockChart.render();
$(function() {
var min = new Date(stockChart.charts[0].axisX[0].minimum),
max = new Date(stockChart.charts[0].axisX[0].maximum);
$("#fromDate").datepicker({
defaultDate: min,
minDate: min,
maxDate: max,
dateFormat: "yy-mm-dd",
onSelect: function(dateText) {
var event = new Event("change");
$($("#stockChartContainer .canvasjs-input-field")[0]).val(new Date(dateText));
$("#stockChartContainer .canvasjs-input-field")[0].dispatchEvent(event);
}
});
$("#fromDate").val(CanvasJS.formatDate(min, "YYYY-MM-DD"));
$("#toDate").datepicker({
defaultDate: max,
minDate: min,
...