CanvasJS changing chart-type based on drop-down value - canvasjs

I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:
<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<script>
window.onload = function () {
var dataPoints = [];
$.getJSON( "<?php echo $url; ?>", function( json ) {
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
</script>
Drop-down list:
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
Thank you in advance.

It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.
Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):
var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
}).done(function(){
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>

Related

How to get jQuery autocomplete value through select dropdown id

I am going to develop three autocomplete dropdown boxes using jQuery ajax for country state and city on my laravel project. I can implement simple html dropdowns using ajax. But while using jQuery autocomplete it automatically adds an input field in which it puts the value over selecting options from dropdown.
The issue is I am getting only values as text string from input field where I need the id of country which is my database. Previously I was able to get this id using html select element by using the value attribute but it seems there no way to get this id from input field.
How to get this and moreover how to use auto complete for multiple select boxes which needs to be auto changed by selecting options from any select boxes?
html select elements
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
#foreach ($countries as $country)
<option value="{{ $country->id }}">
{{ $country->name }}
</option>
#endforeach
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div>
html ajax request
$('#country').change(function(){
var cid = $(this).val();
if(cid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getStates/"+cid,
success:function(res)
{
if(res)
{
$("#state").empty();
$("#city").empty();
$("#state").append('<option>Select State</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
$('#state').change(function(){
var sid = $(this).val();
if(sid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getCities/"+sid,
success:function(res)
{
if(res)
{
$("#city").empty();
$("#city").append('<option>Select City</option>');
$.each(res,function(key,value){
$("#city").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
bootstrap autocomplete code
$( function() {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.attr( "height", "" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: "false"
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.on( "mousedown", function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.on( "click", function() {
input.trigger( "focus" );
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#country" ).combobox();
$( "#toggle" ).on( "click", function() {
$( "#country" ).toggle();
});
} );
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding-top: 2px;
padding-bottom: 5px;
padding-right: 5px;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
<option value="1">
INDIA
</option>
<option value="1">
USA
</option>
<option value="1">
UK
</option>
<option value="1">
AUSTRALIA
</option>
<option value="1">
BRAZIL
</option>
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div></div>

i have an error when use chart on laravel

Can someone can help me? I get an error when I try to use a chart.
Undefined variable: label (View: C:\xampp\htdocs\latihan_penjualan\resources\views\home.blade.php)
in 15bd1eeee4b4d1b903b52322d785ce7ce1ab31d2.php line 31
This is my controller:
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home');
$this->with('value',json_encode($value));
$this->with('label',json_encode($label));
}
And this is my view:
<div id="container" style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script type="text/javascript" src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript" src="http://www.chartjs.org/samples/latest/utils.js"></script>
<script type="text/javascript">
var color = Chart.helpers.color;
var barChartData = {labels: {!! $label !!},
datasets: [{
label: 'Produk Per Kategori',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: {!! $value !!},
}],
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Grafik Data Produk'
}
}
});
};
</script>
I already declared the variable $label.
Thanks in advance.
return view('home')
->with(['value'=>json_encode($value),'label'=>json_encode($label)]);
Fix this part after return view('home');
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home')->with('value',json_encode($value))->with('label',json_encode($label));
}

javascript canvasjs Get data points dynamically from file.txt

Objective:
I want to get data from file.txt thats is saved local in /var/www/html/file.txt and use it for the doughnut chart on my webpage dynamically on a interval of 2 seconds
file.txt only has one entry and looks like:
34
the javascript i have tried:
$.get("file.txt", function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "doughnut",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
Entire html looks like
<!DOCTYPE html>
<html>
<head>
<title>Chart using txtfile Data</title>
<script type="text/javascript" src="http://canvasjs.com/assets/script /jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : [function()
{
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dataPoints.push({x : xVal, y: parseInt(allLines[i])});
}
}
}]
}]
});
chart.render();
},'text');
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I believe something like this may work for you. You may have to use Firefox as Chrome doesn't like cross origin requests
First, dataPoints was undefined, I moved the code into a function inside dataPoints. I changed your variable name from x to xVal. Added the 'text' word so the $get knows what format it's reading and also there was an extra bracket it seemed. Give this a try.
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var dps = [];
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dps.push({x : xVal, y: Number(allLines[i])});
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dps
}]
});
chart.render();
},'text');

CanvasJS Column chart with external json data not loading

Im trying to load this column chart with external data in Json format from a file
I have a jsfiddle with what i have so far.
Thanks for any help.
http://jsfiddle.net/t9n4d8z4/1/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({
label: result[i].label,
y: parseInt(result[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: result
}]
});
chart.render();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
json format was not handled properly.
Here is the working fiddle : http://jsfiddle.net/canvasjs/t9n4d8z4/3/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.dataPoints.length - 1; i++) {
dataPoints.push({
label: result.dataPoints[i].label,
y: parseInt(result.dataPoints[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: dataPoints
}]
});
chart.render();
});
});
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

How to programatically expand a node of Kendo treeview

I have a Kendo treeview that is built as below codes (see below). Each tree node has a unique data id field (that is employee Id).
I would like to have a text box ( <input type="text" ... /> ) and a button ( <input type="button" ... /> ) so user can input some id and when she hit the button, the button click event handler will let the treeview expand the node whose id matches the input id. How can I do that? Thank you very much.
Details of click event handler or the button:
function buttonExpand_onClick()
{
var id = $("textboxEmployeeId").val();
// ???
// how can I do the following code lines to expand the node with id of "id" to see all its children?
}
Details of the existing Kendo treeview building codes:
<div id="treeviewEmployee">
</div>
<script id="treeview-template" type="text/kendo-ui-template">
#: item.text #
</script>
$(function(
{
var defaultRootSelectedId = 1; // 1 is employee id of the root employee on first loading
$.ajax({
url: '/Employee/AjaxGetEmployeeNodes/?id=' + defaultRootSelectedId,
type: 'GET',
dataType: 'json',
async: false,
success: function (data, textStatus, xhr) {
$("#reeviewEmployee").kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: data,
select: treeview_onSelect
});
_treeview = $("#treeviewEmployee").data("kendoTreeView");
},
error:
function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
You can access the datasource on the treeview and find the node by id. I would also like to add that the treeView has a 'findByText()' method as well, in case that is what you want.
HTML
<script id="treeTemplate" type="text/x-kendo-template">
#: item.text #
</script>
<div id="content">
<div id="form">
<label>Node ID:
<input id="nodeId" type="text"/>
</label>
<button id="expandNodeBtn">Expand Node</button>
</div>
<h2>TreeView</h2>
<div id="treeView"/>
</div>
JAVASCRIPT
(function ($) {
$(document).ready(function () {
$("#treeView").kendoTreeView({
dataSource: [
{
text: 'one with id 1',
id: 1,
items: [
{
text: 'one-child-1',
id: 2
},
{
text: 'one-child-2',
id: 3
}
]
},
{
text: 'two with id 4',
id: 4,
items: [
{
text: 'two-child-1',
id: 5
},
{
text: 'two-child-2',
id: 6
}
]
}
]
});
$("#expandNodeBtn").on("click", function(e) {
var val = $("#nodeId").val();
console.log('val: ' + val);
var treeView = $("#treeView").data('kendoTreeView');
var dataSource = treeView.dataSource;
var dataItem = dataSource.get(val); // find item with id = 5
var node = treeView.findByUid(dataItem.uid);
treeView.expand(node);
});
});
})(jQuery);
JSFiddle
I also put together a JSFiddle sample for you to play with: http://jsfiddle.net/jsonsee/D35Q6/
Slightly related, but I came here looking for an answer to this question: How to expand the whole branch when clicking to a parent node in angular treeview? Since I didnt find any answers, I post my solution here. Hope it helps someone.
html
<div id="treeview" kendo-tree-view="tree" k-options="options" k-on-change="selectItem(dataItem)">
</div>
controller
$scope.options = {
dataSource: dummyData,
template: $scope.treeItemTemplate
}
$scope.treeItemTemplate = "<button ng-click='expandRoot(dataItem)'>Blow up</button>";
$scope.expandRoot = function expandRoot(dataItem) {
dataItem.expanded = true;
if (dataItem.hasChildren) {
dataItem.load()
var children = dataItem.children.data();
children.forEach(function (c) {
c.expanded = true;
$scope.expandRoot(c)
});
}
}

Resources