I need to alter value when user select the value from google chart dropdown,
please check the code, I need when user select subject value, then I can alert the message or selected value,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {
packages: ['controls']
});
</script>
<script type="text/javascript">
function drawVisualization() {
// Prepare the data
var jsonData = '{"cols":[{"label":"Subject","type":"string"},{"label":"pete","type":"number"},{"label":"john","type":"number"},{"label":"carl","type":"number"},{"label":"andrea","type":"number"}],"rows":[{"c":[{"v":"coolness"},{"v":4.4},{"v":4.3},{"v":3.1},{"v":4.3}]},{"c":[{"v":"sexyness"},{"v":4.2},{"v":3.8},{"v":3.6},{"v":4.8}]},{"c":[{"v":"toughness"},{"v":3.1},{"v":2.7},{"v":2.4},{"v":2.9}]},{"c":[{"v":"chillnes"},{"v":4.4},{"v":4.4},{"v":4.2},{"v":4.5}]},{"c":[{"v":"madness"},{"v":4.6},{"v":4.6},{"v":4},{"v":4.6}]},{"c":[{"v":"lochness"},{"v":3.9},{"v":3.7},{"v":2.9},{"v":3.9}]},{"c":[{"v":"extraness"},{"v":4.6},{"v":4.3},{"v":3.6},{"v":4.3}]}]}';
console.log(typeof(responseText));
console.log(jsonData);
var data = new google.visualization.DataTable(JSON.parse(jsonData));
var compPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Subject',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': true
}
}
});
// Define a chart
var chart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'title': 'Competenties',
'width': '100%',
'height': 300,
'vAxis': {
viewWindow: {
max: 5,
min: 0
},
gridlines: {
color: '#CCC',
count: 6
}
},
bar: {
groupWidth: '80%'
},
colors: ["#FFC000", "#00b0f0", "#ff0000", "#92d050"]
}
});
// Define a table
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': {
'width': '400px'
}
});
// Create a dashboard
var drawChart = new google.visualization.Dashboard(document.getElementById('dashboard')).bind([compPicker], [chart, table]);;
drawChart.draw(data);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="dashboard">
<table>
<tr style='vertical-align: top'>
<td>
<div id="control1"></div>
<div id="control2"></div>
<div id="control3"></div>
</td>
</tr>
<tr>
<td>
<div style="float: left;" id="chart1"></div>
<div style="float: left;" id="chart2"></div>
<div style="float: left;" id="chart3"></div>
</td>
</tr>
</table>
</div>
</body>
</html>
JS fiddle link
Please help me.
Thanks
Use the 'statechange' event listener to determine when values are selected...
Then compPicker.getState().selectedValues to get the selected values in an array...
google.charts.load('current', {
callback: drawVisualization,
packages: ['controls', 'corechart', 'table']
});
function drawVisualization() {
var jsonData = '{"cols":[{"label":"Subject","type":"string"},{"label":"pete","type":"number"},{"label":"john","type":"number"},{"label":"carl","type":"number"},{"label":"andrea","type":"number"}],"rows":[{"c":[{"v":"coolness"},{"v":4.4},{"v":4.3},{"v":3.1},{"v":4.3}]},{"c":[{"v":"sexyness"},{"v":4.2},{"v":3.8},{"v":3.6},{"v":4.8}]},{"c":[{"v":"toughness"},{"v":3.1},{"v":2.7},{"v":2.4},{"v":2.9}]},{"c":[{"v":"chillnes"},{"v":4.4},{"v":4.4},{"v":4.2},{"v":4.5}]},{"c":[{"v":"madness"},{"v":4.6},{"v":4.6},{"v":4},{"v":4.6}]},{"c":[{"v":"lochness"},{"v":3.9},{"v":3.7},{"v":2.9},{"v":3.9}]},{"c":[{"v":"extraness"},{"v":4.6},{"v":4.3},{"v":3.6},{"v":4.3}]}]}';
var data = new google.visualization.DataTable(JSON.parse(jsonData));
var compPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Subject',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': true
}
}
});
// listen for 'statechange' event on ControlWrapper
google.visualization.events.addListener(compPicker, 'statechange', function () {
// log selected values array
document.getElementById('message').innerHTML += JSON.stringify(compPicker.getState().selectedValues) + '<br/>';
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {'title':'Competenties',
'width':'100%',
'height':300,
'vAxis': {
viewWindow: {max:5,min:0},
gridlines: {color:'#CCC', count: 6}
},
bar: { groupWidth: '80%' },
colors: ["#FFC000","#00b0f0","#ff0000","#92d050"]
}
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': {
'width': '400px'
}
});
var drawChart = new google.visualization.Dashboard(document.getElementById('dashboard'));
drawChart.bind([compPicker], [chart, table]);
drawChart.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<table>
<tr style='vertical-align: top'>
<td>
<div id="control1"></div>
<div id="control2"></div>
<div id="control3"></div>
</td>
</tr>
<tr>
<td>
<div style="float: left;" id="chart1"></div>
<div style="float: left;" id="chart2"></div>
<div style="float: left;" id="chart3"></div>
</td>
</tr>
</table>
</div>
<div id="message"></div>
Related
Still working on my menu and struggling with a new problem.
I want the user to be able to the LI submenus when there is a click on the UL.
The problem is that I don't see how to aim only at the linked LI elements. When I click on any UL, it opens all the LI.
An easy way could be to create different UL in HTML, but I would like to keep this short generated with a loop menu.
How can I aim at the precise UL with the #click event, to open only its child LI?
new Vue({
el: "#app",
data: {
categories: {
Atoms: ['Buttons', 'Icons'],
Molecules: [],
Organisms: [],
Templates: [],
Utilities: ['Grid']
},
openSubCategories: false,
},
})
.doc_nav {
display: flex;
justify-content: around;
}
.doc_nav__ul {
margin: 0 30px;
}
.doc_nav__li {
text-align: center;
}
.doc_nav__li:first-child {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<header class="doc_header">
<nav class="doc_nav">
<ul #click="openSubCategories = !openSubCategories" class="doc_nav__ul" v-for="[ category, subCategories ] in Object.entries(categories)" :key="category"> {{category}}
<template v-if="openSubCategories == true" >
<li class="doc_nav__li" v-for="subCategory in subCategories" :key="subCategory">
{{ subCategory }}
<!-- <router-link :to="subCategory"> {{ subCategory }} </router-link> -->
</li>
</template>
</ul>
</nav>
</header>
</div>
Use CSS to hide li.
I think you can handle it.
new Vue({
el: "#app",
data: {
categories: {
Atoms: ['Buttons', 'Icons'],
Molecules: [],
Organisms: [],
Templates: [],
Utilities: ['Grid']
},
currentActiveCategory: null,
},
method: {
changeClickUl(category) {
if (category == this.currentActiveCategory) this.currentActiveCategory = null
else this.currentActiveCategory = category
}
}
})
.doc_nav {
display: flex;
justify-content: around;
}
.doc_nav__ul {
margin: 0 30px;
}
.doc_nav__ul:not(visible) {
display: none;
}
.doc_nav__li {
text-align: center;
}
.doc_nav__li:first-child {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<header class="doc_header">
<nav class="doc_nav">
<ul #click="changeClickUl(category)" :class="{visible:currentActiveCategory==category}" class="doc_nav__ul" v-for="[ category, subCategories ] in Object.entries(categories)" :key="category"> {{category}}
<li class="doc_nav__li" v-for="subCategory in subCategories" :key="subCategory">
{{ subCategory }}
<!-- <router-link :to="subCategory"> {{ subCategory }} </router-link> -->
</li>
</ul>
</nav>
</header>
</div>
Here is the corrected and working answer of gao.xiangyang
It is using css.
A solution without css: v-if="currentActiveCategory==category"
new Vue({
el: "#app",
data: {
categories: {
Atoms: ['Buttons', 'Icons'],
Molecules: [],
Organisms: [],
Templates: [],
Utilities: ['Grid']
},
currentActiveCategory: null,
},
methods: {
displaySubCategories(category) {
if (category == this.currentActiveCategory) {
this.currentActiveCategory = null
}
else this.currentActiveCategory = category
}
}
})
.doc_nav {
display: flex;
justify-content: around;
}
.doc_nav__ul {
margin: 0 30px;
}
.doc_nav__li:not(visible) {
display: none;
}
.doc_nav__li--visible {
display: block !important;
}
.doc_nav__li {
text-align: center;
}
.doc_nav__li:first-child {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<header class="doc_header">
<nav class="doc_nav">
<ul #click="displaySubCategories(category)" class="doc_nav__ul" v-for="[ category, subCategories ] in Object.entries(categories)" :key="category"> {{category}}
<li :class="{'doc_nav__li--visible' : currentActiveCategory==category}" class="doc_nav__li" v-for="subCategory in subCategories" :key="subCategory">
{{ subCategory }}
<!-- <router-link :to="subCategory"> {{ subCategory }} </router-link> -->
</li>
</ul>
</nav>
</header>
</div>
I have a problem that I even have an idea where to start looking..
So I have a grid and a column of type of receipts. The values are numbers. How can I replace them with meaningfull values (if type is '0', then I need to display 'CASH'). What is the smartest way to do that?
Code:
<?php
require_once(__DIR__ . '/localization/taxesLocalization.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $taxes ?></title>
<link rel="stylesheet" href="styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="styles/kendo.material.min.css" />
<link rel="stylesheet" href="css/custom_style.css">
<link rel="stylesheet" href="HtmlTemplates/notifications.php">
<script src="js/jquery.min.js"></script>
<script src="js/kendo.all.min.js"></script>
<script src="js/devices.js"></script>
<script src="js/functions.js"></script>
<script src="js/FCM.js"></script>
<script src="js/functions/confirm_window.js"></script>
<script src="js/MessageTypes/message_types.js"></script>
<script src="js/functions/show_notification.js"></script>
<script src="js/taxes_scripts/constants.js"></script>
<script src="js/taxes_scripts/functions.js"></script>
<script src="js/functions/duplicates_check.js"></script>
<script src="js/taxes_scripts/services.js"></script>
</head>
<body>
<nav>
<div id="toolbar"></div>
<?php include "navmenu.php"; ?>
</nav>
<span id="popupNotification"></span>
<br>
<div class="" style="width: 100%;">
<div>
<div id="device_container">
<label for="devices" ><b><?php echo $devices ?></b></label>
<input id="device-report" style="width: 270px" />
</div>
</div>
<br>
<div id="gridSession"></div>
<div id="grid"></div>
</div>
</body>
</html>
<script>
var device_ID = 510;
const X_SESSION = "./services/ReportsServices/getXSessionInfo.php?device_ID=";
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: X_SESSION + device_ID,
dataType: "json"
}
},
schema: {
data: "data",
model: {
id: "id",
fields: {
sequence: {},
datestart: {},
total: {},
type: {},
receipt_count: {},
from_ticket: {},
to_ticket: {},
date_start: {},
date_end: {}
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
scrollable: true,
resizable: true,
sortable: true,
filterable: false,
height: $(document).height() - 120,
columns: [
{field: "sequence", title: "Slijed"},
{field: "datestart", title: "Početak sesije"},
{field: "total", title: "Ukupno na računu"},
{field: "type", title: "Način plačanja "},
{field: "receipt_count", title: "Broj računa"},
{field: "from_ticket", title: "Od kartice"},
{field: "to_ticket", title: "Do kartice"},
{field: "date_start", title: "Datum prvog računa"},
{field: "date_end", title: "Datum zadnjeg računa"}
]
}).data("kendoGrid");
$("#device-report").kendoComboBox(
);
});
</script>
You can use template on the grid column which will check the value of type and update the column field accordingly:
{field: "type", title: "Način plačanja", template: "#if (type == 0) {# CASH #} else {# Another value #}#"}
EDIT
Haven't used switch in a template column before but something like this should be pretty close:
{field: "type", title: "Način plačanja", template: "#var value; switch(type){ case 0: value = 'CASH'; break; case 1: value = 'Another value'; break; case 3: value = 'ANOTHER value'; break; default: value = 'Default value'; }##=value#"}
Is there a way to use the export buttons and yadcf chozen filter together without messing up the column headers in the export see below the column Order Number has Select appended
Order NumberSelect
value20766903232802532374885123748865237490732374944323749625x
Code:
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="/newwebadmin/mvc/orders/assets/css/cancellationStatistics.css" />
<link rel="stylesheet" type="text/css" href="/newwebadmin/js/chosen/chosen.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/yadcf/0.9.1/jquery.dataTables.yadcf.css">
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/ChartNew.js"></script>
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/shapesInChart.js"></script>
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/specialInChartData.js"></script>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js"></script>
<script src="/newwebadmin/js/Chosen/chosen.jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/yadcf/0.9.1/jquery.dataTables.yadcf.min.js"></script>
<style>
input[type="search"] {
border:1px #cccccc solid;
padding:2px;
border-radius: 2px;
}
</style>
<title>Cancel Order Reportle></title>
</head>
<cfset local.getCancellationReportData = rc.cancellations>
<body>
<!--- <cfdump var="#local#"> --->
<cfoutput>
<div class="flexbox-container">
<div class="main-content clearfix">
<div class="container">
<form action="" method="post">
<label for="startDate">Date Range: </label>
<input type="text" id="startDate" name="startDate" class="button" value="#structKeyExists(form, "startDate") ? form.startDate : DateFormat(Now(),'mm/dd/yyyy') #">
<label for="endDate">to</label>
<input type="text" id="endDate" name="endDate" class="button" value="#structKeyExists(form, "endDate") ? form.endDate : DateFormat(DateAdd('m',1,Now()),'mm/dd/yyyy') #">
<input type="submit" id="btnFilter" value="Filter" class="button">
</form>
<br><br>
<button id="platinum" class="button">Show Platinum Customers</button>
<button id="nonplatinum" class="button">Show Non-Platinum Customers</button>
<button id="all" class="button">Show All</button>
<br><br>
<table id="report" class="display" cellspacing="0" width="100%">
<thead>
<th align="left">Order Number</th>
<th align="left">VendorID</th>
<th align="left">User Index</th>
<th align="left">Customer Type</th>
<th align="left">Date</th>
<th align="left">## of items cancelled</th>
<th align="left">Total$</th>
<th align="left">Canceled By</th>
<th align="left">Reason</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="5" style="text-align:right">Total:</th>
<th style="text-align:left"></th>
<th colspan="2" style="text-align:left"></th>
<th></th>
</tr>
</tfoot>
<tbody>
<cfloop query="local.getCancellationReportData">
<tr data-isPlatinum="#is_platinum#">
<td>#order_number#</td>
<td>#len(vendorID) ? vendorID: 'unknown'#</td>
<td>#len(dbo_tblEmployee_ID) ? dbo_tblEmployee_ID: 'unknown'#</td>
<td>#customerType#</td>
<td>#DateFormat(date,'mm/dd/yyyy')# #timeFormat(date,'hh:mm TT')#</td>
<td>#qty#</td>
<td align="right">#DollarFOrmat(ExtendedCost)#</td>
<td>#cancelledBy#</td>
<td>#cancellation_reason#</td>
</tr>
</cfloop>
</tbody>
</table>
</div>
</div>
</div>
</cfoutput>
<script>
$(document).ready(function() {
var table = $('#report').DataTable( {
dom: 'Bfrtip',
buttons: [
{extend :'excel', text:'Export to Excel'}
,{extend :'pdf' , text:'Export to PDF', orientation: 'landscape', pageSize: 'LEGAL'}
,'print'
],
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 6 )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b)).toFixed(2);
} );
// Total over this page
pageTotal = api
.column( 6, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b)).toFixed(2);
}, 0 );
// Total over all pages
cantotal = api
.column( 5 )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b));
} );
// Total over this page
canpageTotal = api
.column( 5, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b));
}, 0 );
// Update footer
$( api.column( 6 ).footer() ).html(
'$'+pageTotal +' ( $'+ total +' total )'
);
// Update footer
$( api.column( 5 ).footer() ).html(
''+canpageTotal +' ( out of '+ cantotal +')'
);
}
});
$("#platinum").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
return $(table.row(dataIndex).node()).attr('data-isPlatinum') == 1;
}
);
table.draw();
});
$("#nonplatinum").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
return $(table.row(dataIndex).node()).attr('data-isPlatinum') == 0;
}
);
table.draw();
});
$("#all").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
});
$('.button').button();
var dateFormat = "mm/dd/yy",
from = $( "#startDate" )
.datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
to.datepicker( "option", "minDate", getDate( this ) );
}),
to = $( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
from.datepicker( "option", "maxDate", getDate( this ) );
});
function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}
return date;
};
yadcf.init(table, [
{column_number : 0},
{column_number : 1, filter_type: "multi_select",select_type: 'chosen'},
{column_number : 2},
{column_number : 3},
{column_number : 4},
{column_number : 5},
{column_number : 6},
{column_number : 7},
{column_number : 8},
{column_number : 9}
]);
});
</script>
I have tied this
buttons: [
{extend :'excel', text:'Export to Excel'}
,{extend :'pdf' , text:'Export to PDF', orientation: 'landscape', pageSize: 'LEGAL'
,exportOptions:{
rows: ':not(.notPrintable)'
}
}
,'print'
],
...
yadcf.init(table, [
{column_number : 0},
{column_number : 1, filter_type: "multi_select",select_type: 'chosen'},
{column_number : 2},
{column_number : 3},
{column_number : 4},
{column_number : 5},
{column_number : 6},
{column_number : 7},
{column_number : 8}
]);
$(".yadcf-filter-wrapper").addClass("notPrintable");
This is what worked for me
buttons: [
{extend :'excel', text:'Export to Excel'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
,{extend :'pdf' , text:'Export to PDF'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
,{extend :'print' , text:'Print'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
],
I want to show some dashboard charts (like these ones), for example one PieChart and one BarChart.
The issue I have found is that these charts aren't displayed unless, I right click on Inspect element. And viceversa, if I have the inspect element tools already open, the charts aren't display either until I close the inspect elements tools.
I am using bootstrap, slim framework and eloquent orm.
In the case of the pieChart, the sample data displayed is the following:
[
{
Area: "Actores y Procesos Sociales",
Cantidad: 49
},
{
Area: "Población y Estudios Demográficos",
Cantidad: 41
},
{
Area: "Estudios Agrarios",
Cantidad: 40
},
{
Area: "Instituciones Políticas",
Cantidad: 35
},
{
Area: "Sociedad y Cultura",
Cantidad: 30
},
{
Area: "Estudios Urbanos y Regionales",
Cantidad: 26
},
{
Area: "Estudios de la Educación y la Ciencia",
Cantidad: 23
}
]
Here is the code for both the PieChart and the BarChart:
In the html:
<head>
<link href="http://132.248.234.17/sica15/public/assets/css/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet">
<link href="/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<link href="/assets/css/font-awesome-4.6.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/assets/css/sbadmin2-sidebar-toggle.css" rel="stylesheet" />
</head>
<body>
<div id="page-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
<div id="projectresearcher">
<div id="numberRangeFilter_control_div"></div> <div id="numberRangeFilter_chart_div"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
<div id="institucionesPporproyecto_div">
<div id="numberRangeFilter_control_div_2"></div> <div id="numberRangeFilter_chart_div_2"></div>
</div>
</div>
</div>
</div>
</div>
In the script:
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http:/assets/js/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','controls'],'language': 'es'});
google.charts.setOnLoadCallback(proyectosporarea);
google.charts.setOnLoadCallback(institucionesPporproyecto);
function proyectosporarea() {/*PROYECTOS POR ÁREA*/
var data = new google.visualization.DataTable();
var proyectosporarea = {{proyectosporarea|json_encode|raw}};
var totalproyectos = 0;
data.addColumn('string', 'Área');
data.addColumn('number', 'Cantidad');
$.each(proyectosporarea, function(index, value){
var Cantidad = parseInt(value.Cantidad);
totalproyectos += Cantidad;
data.addRow([value.Area,Cantidad]);
});
var dashboard = new google.visualization.Dashboard(document.getElementById('projectarea'));//var chart = new google.visualization.PieChart(document.getElementById('projectarea'));
// Create a range slider, passing some options
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'numberRangeFilter_control_div',
'options': {
'filterColumnLabel': 'Cantidad'
}
});
// Create a pie chart, passing some options
var pieChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'numberRangeFilter_chart_div',
'options': {
title: 'Número de proyectos vigentes por área de investigación (total: '+totalproyectos+')',
backgroundColor: { fill:'transparent'},
height: 500,
}
});
dashboard.bind(donutRangeSlider, pieChart);
function resizeHandler () {
dashboard.draw(data);//chart.draw(data, options);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
}/*Fin de drawChart() Proyectos por área*/
function institucionesPporproyecto() {/*INSTITUCIONES POR NÚMERO DE PROYECTOS*/
var data = new google.visualization.DataTable();
var proyectosporarea = {{institucionesPporproyecto|json_encode|raw}};
var total = 0;
var totalInvestigadores = 0;
data.addColumn('string', 'Institución');
data.addColumn('number', 'Cantidad');
data.addColumn({type: 'string', role: 'annotation'});
//Sumando los totales para después calcular el porcentaje
$.each(proyectosporarea, function(indice,valor){
var Cantidad = parseInt(valor.Cantidad);
var Total = parseInt(Cantidad);
total += Total;
});
$.each(proyectosporarea, function(index, value){
var Cantidad = parseInt(value.Cantidad);
var Porcentaje = ((Cantidad/total)*100);
if(Porcentaje % 1 != 0){
Porcentaje = Porcentaje.toFixed(0)+'%';
}else{
Porcentaje = Porcentaje + '%';
}
totalInvestigadores=totalInvestigadores+1;
data.addRow([value.Institucion,Cantidad,Porcentaje]);
});
var view = new google.visualization.DataView(data); view.setColumns([0, 1]);
var table = new google.visualization.Table(document.getElementById('institucionesPporproyecto_t'));
table.draw(view, {width: '100%', height: '100%'});
var dashboard2 = new google.visualization.Dashboard(document.getElementById('institucionesPporproyecto_div'));/*Cambie chart por dashboard*/
var control2 = new google.visualization.ControlWrapper({
'controlType':'NumberRangeFilter',
'containerId':'numberRangeFilter_control_div_2',
'options':{
'filterColumnIndex':1,
'minValue':0,
//'maxValue':60,
}
});
var chart = new google.visualization.ChartWrapper({
'chartType':'BarChart',
'containerId':'numberRangeFilter_chart_div_2',
'options':{
title: 'Número de proyectos por institución participante (Total de Instituciones: '+totalInvestigadores+').',
chartArea: {width: '45%'},
hAxis: {
title: 'Cantidad de proyectos',
minValue: 0
},
vAxis: {
title: 'Instituciones'
},
height: 1400,
//width: 1200,
}
});
dashboard2.draw(view);//chart.draw(view);
google.visualization.events.addListener(table, 'sort',
function(event) {
data.sort([{column: event.column, desc: !event.ascending}]);
dashboard2.draw(view);//chart.draw(view);
});
//chart.draw(data, options); Aquí ando
dashboard2.bind(control2,chart);
function resizeHandler () {
dashboard2.draw(data);//chart.draw(data, options);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
}/*Fin de drawChart() Tabla Instituciones por número de proyectos*/
</script>
Why is this happening? What should I fix so that those charts are displayed just after opening the URI in the browser?
Solved
The problem was in this part where there is this function resizeHandler():
I had:
dashboard2.bind(control2,chart);
/*http://stackoverflow.com/a/18984903/1883256*/
function resizeHandler () { /*This helps make the chart responsive*/
dashboard2.draw(data);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
Instead of:
dashboard2.bind(control2,chart);
dashboard2.draw(data);
/*http://stackoverflow.com/a/18984903/1883256*/
function resizeHandler () {/*This helps make the chart responsive*/
dashboard2.draw(data);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
So, I had to repeat the call of the dashboard.draw(data); both inside the function resizeHandler() and outside it, below the dashboard.bind() function.
first, setOnLoadCallback should only be called once per page load
and you can include the 'callback' in google.charts.load
try replacing this...
google.charts.load('current', {'packages':['corechart','table','controls'],'language': 'es'});
google.charts.setOnLoadCallback(proyectosporarea);
google.charts.setOnLoadCallback(institucionesPporproyecto);
with this...
google.charts.load('current', {
'callback': function () {
proyectosporarea();
institucionesPporproyecto();
},
'packages': ['corechart','table','controls'],
'language': 'es'
});
next, each wrapper object needs a dom element
in function proyectosporarea, the objects appear to have the wrong containerId
see comments in the following snippet...
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div', //<-- should = numberRangeFilter_control_div
'options': {
'filterColumnLabel': 'Cantidad'
}
});
// Create a pie chart, passing some options
var pieChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div', //<-- should = numberRangeFilter_chart_div
'options': {
title: 'Número de proyectos vigentes por área de investigación (total: '+totalproyectos+')',
backgroundColor: { fill:'transparent'},
height: 500,
}
});
In order to create horizontal bar charts using Chart.js I added Chart.HorizontalBar.js to my project. The problem is that bars are drawn from top to down in descending order and I need exactly the opposite.
Does anyone has an idea on how to change the order? I spend hours researching but I could not find any solution.
Thank you
drawn from top to down in descending order
<!doctype html>
<html>
<head>
<title>Horizontal Bar Chart</title>
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<script src="../Chart.HorizontalBar.js"></script>
</head>
<body>
<div style="width: 50%">
<canvas id="canvas" class="chart-base" chart-type="type"
chart-data="data" chart-labels="labels" chart-legend="true">
</canvas>
</div>
<script>
var barChartData = {
labels : ["Facebook Inc Class A","Amazon.com Inc","Allergan PLC"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [9,8,7]
}
]
};
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
var chart = new Chart(ctx).HorizontalBar(barChartData, {
responsive: true,
barShowStroke: false,
scaleBeginAtZero: true
//scaleLabel: "<%=label%>"
});
};
</script>
</body>
</html>
Just swap the order in the input i.e.
var barChartData = {
labels: ["Allergan PLC", "Amazon.com Inc", "Facebook Inc Class A"],
datasets: [{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [7, 8, 9]
}]
};