Flot PIE chart with optional series - javascript

Im using the library Flot in combination with pie charts.
Now I got my chart working but I also need to be able to select what series will be visible. I've seen several examples using checkboxes and regular charts(line, bar). But I haven't seen one example using pie charts.
So here's the code I used to make it work with pie charts, but without success.
function setKPI(data, id)
{
var i = 0;
$.each(data, function(key, val) {
val.color = i;
++i;
});
// insert checkboxes
var choiceContainer = $("#choices");
$.each(data, function(key, val)
{
choiceContainer.append("<br/><input type='checkbox' name='" + key +
"' checked='checked' id='id" + key + "'></input>" +
"<label for='id" + key + "'>"
+ val.label + "</label>");
});
choiceContainer.find("input").click(plotAccordingToChoices);
function plotAccordingToChoices()
{
var data1 = [];
choiceContainer.find("input:checked").each(function ()
{
var key = $(this).attr("name");
if (key && data[key]) {
data1.push(data[key]);
}
});
if (data1.length > 0)
{
$.plot(id, data1,
{
series:
{
pie:
{
show: true,
innerRadius: 0.4,
},
},
legend: {show: false}
});
}
}
plotAccordingToChoices();
}
var datasets = new Array();
datasets[1] = [
{label: "New", data: 51},
{label: "Plan", data: 20},
{label: "Comm", data: 25},
{label: "Done", data: 100},
{label: "Overdue", data: 20},
];
setKPI(datasets[1],'#kpi-2');
This code seems to work the first time it's run but whenever there's a checkbox unticked it draws an invalid line chart.
HTML:
<div id="kpi-2" style="width:100%;height:220px;margin:0 auto;"></div>
<p id="choices" style="float:right; width:135px;"></p>

Found the answer here: Refresh/Reload Flot In Javascript
thus using
plot.setData(newData);
plot.draw();
full example below
function setKPI(data, id, check, options)
{
setColors(data);
createFlot(data, id);
var plot = $.plot($(id),data,options);
if(check)
{
insertCheckboxes(data);
var choiceContainer = $("#choices");
choiceContainer.find("input").on('click', function(){
resetKPI(data, plot);
});
}
}
function resetKPI(data, plot)
{
var choiceContainer = $("#choices");
var newData = [];
choiceContainer.find("input:checked").each(function ()
{
var key = $(this).attr("name");
if (key && data[key]) {
newData.push(data[key]);
}
});
plot.setData(newData);
plot.draw();
}
function createFlot(data, id, options)
{
$.plot(id, data, options);
}
function setColors(data)
{
var i = 0;
$.each(data, function(key, val) {
val.color = i;
++i;
});
}
function insertCheckboxes(data)
{
var choiceContainer = $("#choices");
$.each(data, function(key, val)
{
choiceContainer.append("<br/><input type='checkbox' name='" + key +
"' checked='checked' id='id" + key + "'></input>" +
"<label for='id" + key + "'>"
+ val.label + "</label>");
});
}
using the following data
datasets[1] = [
{label: "New", data: 51},
{label: "Plan", data: 20},
{label: "Comm", data: 25},
{label: "Done", data: 100},
{label: "Overdue", data: 20},
];
calling function
setKPI(datasets[1],'#kpi-2', true, {
series:
{
pie:
{
show: true,
innerRadius: 0.4,
},
},
legend: {show: false}
});

Related

How to use JSON data to populate a d3 chart (highcharts)

var units = {
title: 'override'
};
var optionsPie = {
chart: {
renderTo: 'existingOrNew-chart',
defaultSeriesType: 'pie'
},
title: {
text: 'new'
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y + ' ' + units.title+Math.round(this.percentage*100)/100 + ' %';
}
},
credits: {
enabled: false
},
exporting: { enabled: false },
series: []
};
$(document).ready(function() {
$.get('csvFiles/ExistingNew.csv', function(data) {
var seriesPie = {
data: []
};
console.log(data);
console.log(obj.Sheet6);
var seriesPieItem = new Array();
var lines = data.split('\n');
console.log(lines);
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if (lineNo == 0) {
$.each(items, function(itemNo, item)
{
if (itemNo == 0) optionsPie.title.text = item;
if (itemNo == items.length - 1) units.title = item;
});
}
else
{
seriesPieItem = new Array();
$.each(items, function(itemNo, item)
{
if (itemNo == 0)
{
seriesPieItem.push(item);
}
else
{
seriesPieItem.push(parseFloat(item));
}
});
seriesPie.data.push(seriesPieItem);
}
});
optionsPie.series.push(seriesPie);
var chart = new Highcharts.Chart(optionsPie);
});
});
<div class="row">
<div class="my-3 mx-auto">
<div class="card" style="position: relative; width: 60vw;">
<div class="card-title text-center">
<h4><b>Existing or New Customer</b></h4>
</div>
<div id="existingOrNew-chart"></div>
</div>
</div>
</div>
This d3 chart is from highcharts. I used a csv file's data to populate this chart.
And I have this json Data:
{
"Sheet6": [
{
"RowLabels": "Existing",
"CountOfClientName": 21
},
{
"RowLabels": "New",
"CountOfClientName": 28
}
]
}
Now I have included a new feature that is uploading an xlsx file. But first I have to convert the xlsx file data into json data and use that in the chart. I made the conversion and I got the Json data above .How can I use the "Sheet6" data in the chart. Instead of using the csv file data, is it possible to use the json data("Sheet6") in the chart?. Can you please help me. Thank You

Passing data into chart using HTML and JavaScript

The following code is used to display a chart. The problem is the "data" is hard coded in. How can I change this so that the chart displays values which are displayed using:
<div id="name"> </div>
<div id="testscore"></div>
The above 2 div's contain dynamic values. I want to display these values in the chart.
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
// title:{
// text: "Olympic Medals of all Times (till 2012 Olympics)"
// },
animationEnabled: true,
legend: {
cursor:"pointer",
itemclick : function(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
},
axisY: {
title: "Time"
},
toolTip: {
shared: true,
content: function(e){
var str = '';
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= 'color:"+e.entries[i].dataSeries.color + "'> " + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<span style = 'color:DodgerBlue; '><strong>"+e.entries[0].dataPoint.label + "</strong></span><br/>";
str3 = "<span style = 'color:Tomato '>Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
},
data: [
{
type: "bar",
showInLegend: true,
name: "Black",
color: "#000000",
dataPoints: [
{ y: 0.18, label: "Name"},
{ y: 0.12, label: "Name 1"},
{ y: 0.59, label: "Name 2"},
{ y: 1.15, label: "Name 3"},
]
},
]
});
chart.render();
}
</script>
You can simply call
var data = document.getElementById('name').value;
var data2 = document.getElementById('testscore').value;
If it's a single value, it would work; otherwise, you need to do it this way:
var array = $('#your.id').data('stuff');
Here, "stuff" is nothing but
<div data-stuff="some data" ></div>
Or, create an array by:
var array = new Array();
and finally, store the data into the array.

Construct JSON in proper format with Jquery

I am trying to reformat a dynamically created JSON output into a format that can be consumed by the x-editable select type source[]. I need help building the array so that the re-formated JSON output looks like this:
{value: 2, name: 'Maintenance'},
Below is a sample original JSON which I am consuming:
{"COLUMNS":["SECTIONCOMMONNAME"],"DATA":[["Aircraft Overview"],["Email Server Settings"],["Maintenance"],["Page Sections"],["WOW"]]}
The code I am using is:
$(document).ready(function () {
var myURL = 'https://api.myjson.com/bins/3nzdj';
var myarray = [];
$.ajax({
url: myURL,
dataType: 'json',
success: function (e) {
console.log('My created console output:' +'<br>');
$.each(e.DATA, function (i, jsonDataElem) {
console.log("{value: " + i + ', ' + "name: " + '"'+this+"'}");
var item = {
"value": i,
"name": this
};
myarray.push(item);
});
var newJson = JSON.stringify(myarray);
console.log('My stringify output:' +'<br>' +newJson);
}
});
$('.sectionsAvailable').editable({
name: 'template',
type: 'select',
placement: 'right',
send: 'always',
value: 1,
source: [], //newJson (my new var)
/* should be in this format:
source: [{
value: 1,
text: 'text1'
}, {
value: 2,
text: 'text2'
}]*/
});
};
});
After the stringify, the output is close, but wont work. It looks like this:
{"value":2,"name":["Maintenance"]}
and needs to look like thisL
{value:2,name:'Maintenance'},
Here is a JSfiddle showing the output here.
it seems you are assigning complete array instead of value at index 0 try this
var item = {
"value": i,
"name": this[0] // gives elemnt at index 0
};
myarray.push(item);
FIDDLE
I was able to answer my own question. There might be a better way, but this works:
var myURL = 'https://api.myjson.com/bins/3nzdj';
$.getJSON(myURL, function(data) {
var output = '';
$.each(data.DATA, function(key, val) {
output +='{value: ';
output += "'"+key+"'";
output +=',text:';
output += "'"+val+"'";
output +='}';
output +=',';
});
var outputAdapted = '['+output+']'
$('.sectionsAvailable').editable({
name: 'template',
type: 'select',
placement: 'right',
send: 'always',
value: 1,
// should be in this format:
source:
function() {
return outputAdapted;
},
});
});
My FIDDLE I hope this can help someone else.

Hide column in jQuery MultiColumn Autocomplete

I have a fine working jquery multicolumn autocomplete. Now i have to add a column which should be hidden. Basically its a ID of the values. So when the user selects the value i could able to get the ID of the selected row.
//Code:
<script type="text/javascript">
var autocompleteSource;
var colValues = [];
var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
$.ajax({
url: "/Home/LoadWorkflowDropdown",
datatype: 'json',
mtype: 'GET',
success: OnComplete,
error: OnFail
});
function OnComplete(result) {
autocompleteSource = $.parseJSON(result)
$.each(autocompleteSource, function () {
colValues.push([this.WorkflowName, this.WorkflowCategory, this.StatusName, this.UserName]);
});
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colValues,
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
}
</script>
Working Fiddle here
Here i have modified js code to add unique id to each record and to get that value when user selects a particular option from the auto-suggest list. Fiddle
HTML: Create a hidden field to store the id of selected option
<input type="hidden" name="selectedId" id="selectedId" />
JS: Added ids in the array and retrieved those ids in select function by index value.
var columns = [{
name: 'Color',
width: '100px'},
{
name: 'Hex',
width: '70px'}],
colors = [['Red', '#f00', '1'], ['Green', '#0f0', '2'], ['Blue', '#00f', '3']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
$('#selectedId').val(ui.item[2]);
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});

Change JQGrid Cell value on Button Click

I am using jqgrid in asp.net webforms. I have a column which name is Actions, in which I have button Add I want that when I click on add button, then cell value should be changed. Like I have button in this cell, when I click on add button, then it should change with text. Please, guide me. Code is given below which i am using.
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
 
jQuery("#jQGridDemo").jqGrid({
url: 'HttpHandlers/CustomersList.ashx',
datatype: "json",
colNames: ['Opted-In', 'Name', 'Email', 'Filter Matches', 'Customer Id','Actions'],
colModel: [
{ name: 'OptedIn', index: 'OptedIn', width: 40,align:'center', stype: 'text', formatter: OptedInValue },
{ name: 'CustomerName', index: 'CustomerName', width: 90, stype: 'text', sortable: true },
{ name: 'CustomerEmail', index: 'CustomerEmail', width: 110, stype: 'text', sortable: true },
{ name: 'FilterLetter', index: 'FilterLetter', width: 60 },
{ name: 'CustomerId', index: 'CustomerId', width: 60, hidden: true },
{ name: 'Actions', index: 'Actions',editable:true, width: 60,align:'center',formatter: ButtonValue }
],
width: 600,
height:300,
rowNum: 30,
mtype: 'GET',
loadonce: true,
rowList: [30, 60, 90],
pager: '#jQGridDemoPager',
sortname: 'OptedIn',
viewrecords: true,
sortorder: 'asc',
caption: "Customer List"
});
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var link = '';
if (filterLetter == " A") {
link = '<button type="button" onclick=addGridCustomer(' + rowObject.CustomerId +')>Add</button>';
} else {
link = '<div id="rowelder"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId +')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id,rowId) {
debugger
var rowData = $('#jQGridDemo').jqGrid('getRowData', rowId);
rowData.Actions = '12321';
$('#jQGridDemo').jqGrid('setRowData', rowId, rowData);
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
UpdateFiltersForCusRemove(id);
}
i work on this problem and found the solution here below is the problem of my solution.
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var Id = qs("id");
var link = '';
if (Id != 0) {
link = '<div id="addbutton"><button type="button" onclick=addGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Add</button></div>';
}
else {
link = '<div id="removecustomer"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id, rowId) {
debugger
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be removed ..');
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
//Update Filters in case of removal
UpdateFiltersForCusRemove(id);
}
function addGridCustomer(id, rowId) {
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be added ..');
//Update Filters in case of removal
UpdateFiltersForCusAdd(id);
}
function UpdateFiltersForCusAdd(a) {
var filterLtr = $("#lblF" + a).text().trim();
var count = 0;
count = parseInt($("#filterL" + filterLtr).text().trim()) - 1
$("#filterL" + filterLtr).text(count);
TotalCustomers(+1);
}

Categories