I have a Morris donut/pie char that I initialize like following:
function InitializePieChart(data) {
var formedData = "";
var length = Object.keys(data).length;
$.each(data, function (index, value) {
if (index === (length - 1)) {
formedData += "{ value: '"+value.Percentage+"' , label: '" + value.SellerName + "' }";
}
else {
formedData += "{ value: '"+ value.Percentage + "' , label: '"+ value.SellerName + "' } , ";
}
});
console.log(formedData);
Morris.Donut({
element: 'pie-chart',
data: [JSON.stringify(formedData)],
backgroundColor: 'transparent',
labelColor: '#6d6d6d',
colors: [
'#012e42',
'#076178',
'#0f7c93',
'#1b99ac'
],
formatter: function (x) { return x + " %" }
});
}
As you can see here the value for the donut chart should be set to the "Percentage" property of the returned JSON, and the label should be set to the "SellerName" property...
However whatever I tried didn't work.. The returned JSON contains more properties than these two but they are irrelevant for this chart... I tried forming a JSON to inject it into the chart , but it returns as empty when the page is rendered completely..
Is there any way I can just simply inject the data into chart directly and then specify which property belongs to "label" and which belongs to "value" ?
Can someone help me out with this one?
Related
I want displaying object data in table, which value inside name of object appear as <td>,
i have result in the network preview like this below:
I need displaying value inside A1_score and A2_score as <td>, so i tried jquery like this:
$(document).on('click', '#cektesting', function(e) {
$('.row').css({ 'visibility': 'hidden', 'display': 'none' });
$.ajax({
url: "pengguna/getCounting",
type: "GET",
dataType: "JSON",
success: function(data) {
$('.row').css({ 'visibility': 'visible', 'display': 'flex' });
$.each(data['A1_score', 'A2_score'], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + value + '</td><td>' + value + '</td></tr> '
);
});
}
});
});
And last thing those data came from my Controller.php:
public function getCounting()
{
$get_row_class = $this->getdata->getAutism();
$get_row = $this->getdata->countrow();
$row_autism = $get_row_class['Autism'];
$row_normal = $get_row_class['Normal'];
$res_autism = number_format($row_autism / $get_row['jml_data_latih'], 6);
$res_normal = number_format($row_normal / $get_row['jml_data_latih'], 6);
$A_Score = $this->getdata->getA_score();
$data = [];
foreach ($A_Score as $as) {
$row['A_Y_NORMAL'] = $as['A1_YES_NORMAL'] / $row_normal;
$row['A_Y_AUTIS'] = $as['A1_YES_AUTIS'] / $row_autism;
$row['A_N_NORMAL'] = $as['A1_NO_NORMAL'] / $row_normal;
$row['A_N_AUTIS'] = $as['A1_NO_AUTIS'] / $row_autism;
$row2['A_Y_NORMAL'] = $as['A2_YES_NORMAL'] / $row_normal;
$row2['A_Y_AUTIS'] = $as['A2_YES_AUTIS'] / $row_autism;
$row2['A_N_NORMAL'] = $as['A2_NO_NORMAL'] / $row_normal;
$row2['A_N_AUTIS'] = $as['A2_NO_AUTIS'] / $row_autism;
$data['A1_score'] = $row;
$data['A2_score'] = $row2;
}
echo json_encode($data);
}
Result:
And this is what i get when i tried build jquery from jquery code above, So i get A2_score data but A1_score didn't displaying only A2_score data get looped.
You can get all keys inside your object and then use that keys to get required data from both JSON Object .
Demo Code :
//just for demo..
var data = {
"A1_score": {
"xs": 12322,
"sse": 1232
},
"A2_score": {
"xs": 1234,
"sse": 213
}
}
//get keys of one object because keys in other object are same
var keys = Object.keys(data["A1_score"])
console.log(keys)
//loop through keys
for (var i = 0; i < keys.length; i++) {
var keys_ = keys[i]
//add that inside your table
$('#tbodyres').append(
'<tr class="idscore"><td>' + keys_ + '</td><td>' + data["A1_score"][keys_] + '</td><td>' + data["A2_score"][keys_] + '</td></tr> '
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbodyres"></table>
You can not use data['A1_score', 'A2_score'] to iterate over properties A1_score & A2_score. What you should do is iterate over either A1_score or A2_score and retrieve key. Then get values from A1_score & A1_score with data["A1_score"][key] & data["A2_score"][key].
Try like below.
$.each(data["A1_score"], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + data["A1_score"][key] + '</td><td>' + data["A2_score"][key] + '</td></tr> '
);
});
I'm picking up a JSON object using a promise:
var x = get();
x.done(function(data) {
for(var i in data) {
}
});
which is returning this data when i do console.log(data);
[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)
so that is working fine, but within my for loop, I want to add 2 items to data
I tried adding this into my .done
var obj = { name: "Light" };
data.push(obj);
But that didn't add to data
My for loop looks like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them.
In the simplest case, it could be as straightforward as
x.done(function(data) {
data.push({ "data": { "name": "light", "id": 1234 } });
data.push({ "data": { "name": "dark", "id": 5678 } });
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if (data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
});
Demo: https://jsfiddle.net/a286b7fw/1/
In this case I think data is not an array so it hasn't .push() method. You can add property to object like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
// here it will add obj to data
var obj = {name: "Light"};
data = {
...data,
obj
}
}
My page has search box to filter particular column data.The text in the cell is displayed using html properties like <i> and <b>.
So it is a challenge for me to filter the text with <i> or <b>.
Here is html code for search box.
<form>
<span>EnglishStaffname</span>
<input type='text' id='EnglishStaffname_search' value=""></input>
</form>
The script to create datatable is below:
function createWidget(table) {
column_data = [
{title: "User ID", visible: false, data: "id"},
{title: "Location", visible: true, data:"location"},
title: "Details",
data: "details",
sortable: false,
render: {
display: function(data) {
json = jQuery.parseJSON(data);
s = "";
if ("subjects" in json)
{
s += "<b>subjects:</b><br />";
$.each(json["subjects"], function(key, value) {
s += " - <i>" + key + ": </i>" + value + "<br />";
});
s += "<b>hours:</b><br />";
$.each(json["hours"], function(key, value) {
s += " - <i>" + key + ": </i>" + value + "<br />";
});
}
else
{
$.each(json, function(key, value) {
s += "<b>" + key + ": </b>" + value + "<br />";
});
}
return s;
}
}
}];}
The table displays the details column like below
1st row :
subject:
-English:Meena.K
-Maths:Ramya.v
hours:
-monday:8
2nd row:
English:Kiran.K
Maths:Ramya.v
I have tried to filter details column for English using jquery something like this:
$("EnglishStaffname_search").keyup(function() {
try {
item = $(this).val();
table.column(2).search(item, true, false).draw();
} catch(e) {
}
});
But the above is searching for whole cell not for only English.I have tried regex also but not getting exact match.
Can any one suggest me to get exact match irrespective of html tags?
Web page table:
We can do it using RegEx.
Try following code-
$(document).ready(function() {
var table = $('#example').DataTable( {
responsive: true
});
$('input[type="search"]').keyup(function(){
var term = $(this).val();
if(term =='') {
regex = '';
} else{
regex = 'English:'+ term ;
}
table.search( regex, true, false ).draw();
})
});
Working jsfiddle.
By javascript I generate rows for Agents in a table. every row represent an agent. after this I receive live data to update the columns. I have a column called (Calls) and i need to order the agents by calls (live update depending on received data) descending. example
agents ----- calls
Sam ---------13
Al ---------12
Sara---------8
if Sara got the most data by time then she'll be the first.
agents -------calls
Sara----------15
Sam ----------13
Al------------12
and so on ..
this is my row rendering
var $agentRow = '<tr id="agentRow_' + agentId + '"><th scope="row">' + agentName + '</th><td class="calls" id="agentCalls_' + agentId + '">' + outTotalCalls +
'</td><td class="minutes" id="agentMinutes_' + agentId + '">' +
outCallMinutes + '</td>' +
'<td class="averages" id="agentAverage_' + agentId + '">' + averageOutCallTime + '</td></tr>';
//if $agentRow exists invoke setIncomingValuesToAgentsFields else append it to the table
if ($('#agentRow_' + agentId).length) {
setIncomingValuesToAgentsFields('#agentCalls_' + agentId, outTotalCalls);
setIncomingValuesToAgentsFields('#agentMinutes_' + agentId, outCallMinutes);
setIncomingValuesToAgentsFields('#agentAverage_' + agentId, averageOutCallTime);
} else {
$('#agentsTable').append($agentRow);
}
function setIncomingValuesToAgentsFields(elementId, inComingValue) {
var currentElementValue = 0;
if ($(elementId).text() !== "") {
currentElementValue = $(elementId).text();
currentElementValue = parseFloat(currentElementValue);
currentElementValue += inComingValue;
$(elementId).text(currentElementValue);
} else {
$(elementId).text(currentElementValue);
}
}
See the live sample of what you need. After 3 second Al calls become 14, and table rows will be sorted again.
var agents = [
{ name: 'Sara', calls : 15 },
{ name: 'Sam', calls : 13 },
{ name: 'Al', calls : 12 }
];
function to_row(obj){
var tr = $('<tr></tr>');
tr.data('obj', obj);
$('<td>'+obj.name+'</td>').appendTo(tr);
$('<td>'+obj.calls+'</td>').appendTo(tr);
return tr;
}
function table_update(obj){
$('#table tr').each(function(){
var t=$(this);
var o=t.data('obj');
if(o.name==obj.name){
t.remove();
};
if(o.calls>obj.calls){
to_row(obj).insertAfter(t);
}
return t.data('obj');
})
}
agents.sort(function(x,y){
return y.calls - x.calls;
}).forEach(function(o){
to_row(o).appendTo( $('#table') );
});
setTimeout(function(){
table_update( { name: 'Al', calls : 14 } );
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>
Hope you will be getting data from server using Ajax call . So If your having the result data in JSON object , then you can sort the data to find out which is having highest value . The follwing functon will help us to sort the data
sortTable:function (property,asc)
{
sampleTableObject = sampleTableObject.sort(function(a, b) {
if (asc) return (a[property] > b[property]) ? 1 : ((a[property] < b[property]) ? -1 : 0);
else return (b[property] > a[property]) ? 1 : ((b[property] < a[property]) ? -1 : 0);
});
}
property is the json object property (here it should be calls) based on which you need to sort .
Pass false to 'asc' to sort in descending order.
Assign sampleTableObject with the result json object and call sortTable() . Then use the sorted object to build the table.
Scenario:
I am taking data from an external json file, parsing it, and then appending it to an HTML table that is using the footable jquery plug-in.
Question:
This is a total noob question......but does anyone know (or could provide an example of) how to use javascript to parse that json file....and depending on the value of one of the name/value pairs, display that text in a different color within the table? Currently, everything is displaying in plain text.
COPD_QUAL.MED_ASSESS is the object that I would like to display differently depending on the value. So I would need something like....
if COPD_QUAL.MED_ASSESS == "Mild exacerbation"......display in green, bold text
if COPD_QUAL.MED_ASSESS == "Moderate exacerbation"......display in yellow, bold text
if COPD_QUAL.MED_ASSESS == "Severe exacerbation"......display in red, bold text
Below is the way I currently have the data appending the table. Can anyone help with incorporating an if / condition to accomplish the above? Do I need to add it within my createPatientTable function?
if (window.location.hostname == 'localhost') {
console.log('local');
$.ajax({
type : 'GET',
url : 'json/gtw_copd_mpage3.json',
dataType : 'json',
success : function(json) {
createPatientTable(json);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}else{
var getPatients = new XMLCclRequest();
getPatients.onreadystatechange = function () {
if (getPatients.readyState == 4 && getPatients.status == 200) {
var json = $.parseJSON(getPatients.responseText);
createPatientTable(json);
};
}
};
});
function createPatientTable(json) {
$.each(json.LIST, function(i, COPD_QUAL) {
$('.footable > tbody:last').append('<tr><td>' + COPD_QUAL.PATIENT + '</td><td>' + COPD_QUAL.FIN +'</td><td>' + COPD_QUAL.NURSE_UNIT + '</td><td>' + COPD_QUAL.ROOM + '</td><td>' + COPD_QUAL.BED +'</td><td>' + COPD_QUAL.ATTENDING_PHYS + '</td><td>' + COPD_QUAL.LENGTH_OF_STAY + '</td><td>' + COPD_QUAL.MED_ASSESS + '</td></tr>');
});
$('.footable').footable();
};
Here is one of the json arrays within the file:
{"COPD_QUAL":"15","LIST":[ {"PATIENT":"TEST, TRICKLE","FIN":"70100905","NURSE_UNIT":"TIC","ROOM":"C219","BED":"A","ATTENDING_PHYS":"LEVITEN , DANIEL L","LENGTH_OF_STAY":"161days 20:15:24","MED_ASSESS":"Mild exacerbation"}...
My suggestion would be something like this:
/* ... */
+ '</td><td>' + COPD_QUAL.LENGTH_OF_STAY +
'</td><td class="assessment ' + getSeverity(COPD_QUAL.MED_ASSESS) + '">' +
COPD_QUAL.MED_ASSESS + '</td></tr>')
with
getSeverity = (function() {
var lookup = {
"Mild exacerbation": "mild",
"Moderate exacerbation": "moderate",
"Severe exacerbation": "severe" // presumably you didn't mean two milds...
};
var defaultValue = "unknown"
return function(assessment) {
return lookup[assessment] || defaultValue;
};
}());
and CSS like:
.assessment {font-weight: bold;}
.mild {color: green;}
.moderate {color: yellow;}
.severe {color: red;}
Can you not just add an if condition that attaches a class to the appropriate row:
var class = '';
if(COPD_QUAL.MED_ASSESS == "Mild exacerbation"){
class = 'mild';
} else if (COPD_QUAL.MED_ASSESS == "Moderate exacerbation") {
class = 'moderate';
} else if (COPD_QUAL.MED_ASSESS == "??? exacerbation") {
class = 'severe';
}
then change your tr to:
"<tr class="' + class + '">...
And set up the styling for .mild, .moderate, .severe in a CSS file.