DataTables using Export Buttons and YADCF causes select lists to be exported - coldfusion

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;
}
}
}
}
],

Related

Data is not displayed on the browser from the blockchain server on solidity

I am trying to make a voting app using Blockchain on truffle framework. The data from the network is not rendered on the webpage.
Only loading is displayed but the actual content is not displayed even though I have connected by Blockchain accounts from Ganache to my metamask extension.
Here is my code:
Election.sol
pragma solidity ^0.5.0;
contract Election {
// Model a Candidate for first past the post system
struct Candidatepost {
uint id;
string name;
uint voteCount;
}
// Model as candidate for proportional party system
struct Candidateparty {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidatepost) public cand_post;
mapping(uint => Candidateparty) public cand_party;
// Store Candidates Count
uint public partyCount;
uint public postCount;
uint[] public candidatesCount = [postCount,partyCount];
constructor () public {
addpostCandidate("Candidate 1");
addpostCandidate("Candidate 2");
addpartyCandidate("Candidate 1");
addpartyCandidate("Candidate 2");
candidatesCount = [postCount,partyCount];
}
function addpostCandidate (string memory _name) private {
postCount ++;
cand_post[postCount] = Candidatepost(postCount, _name, 0);
}
function addpartyCandidate (string memory _name) private {
partyCount ++;
cand_party[partyCount] = Candidateparty(partyCount, _name, 0);
}
// voted event
event votedEvent (
uint indexed _candidateId1,
uint indexed _candidateId2
);
function vote (uint _candidateId1, uint _candidateId2) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId1 > 0 && _candidateId1 <= postCount && _candidateId2 > 0 && _candidateId2 <= partyCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
cand_post[_candidateId1].voteCount ++;
cand_party[_candidateId2].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId1, _candidateId2);
}
}
App.js
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded
App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
//load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(1) {
var postcandidatesResults = $("#postcandidatesResults");
postcandidatesResults.empty();
var partycandidatesResults = $("#partycandidatesResults");
partycandidatesResults.empty();
var postcandidatesSelect = $('#postcandidatesSelect');
postcandidatesSelect.empty();
var partycandidatesSelect = $('#partycandidatesSelect');
partycandidatesSelect.empty();
for (var i = 1; i <= 2; i++) {
electionInstance.cand_post(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>";
postcandidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</ option>";
postcandidatesSelect.append(candidateOption);
});
}
for (var j = 1; j <= 2; j++) {
electionInstance.cand_party(i).then(function(candidate) {
var id2 = candidate[0];
var name2 = candidate[1];
var voteCount2 = candidate[2];
// Render candidate Result
var candidateTemplate2 = "<tr><th>" + id2 + "</th><td>" + name2 + "</td><td>" + voteCount2 + "</td></tr>";
partycandidatesResults.append(candidateTemplate2);
// Render candidate ballot option
var candidateOption2 = "<option value='" + id2 + "' >" + name2 + "</ option>";
partycandidatesSelect.append(candidateOption2);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote
if(hasVoted) {
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId1 = $('#postcandidatesSelect').val();
var candidateId2 = $('#partycandidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId1, candidateId2, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Election Results</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">
<div class="row d-flex justify-content-center" style="border:none;background:white;">
<div class="col-md-1 col-3">
<img class="mx-auto d-block img-fluid" src="images/logo.png" style="" alt="">
</div>
</div></h1>
<hr/>
<br/>
<h1 class="text-center">National Election-2075</h1>
<h1 class="text-center">Election Updates</h1>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="postcandidatesResults">
</tbody>
</table>
<hr/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="partycandidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="postcandidatesSelect">Select Candidate</label>
<select class="form-control" id="postcandidatesSelect">
</select>
</div>
<div class="form-group">
<label for="partycandidatesSelect">Select Candidate</label>
<select class="form-control" id="partycandidatesSelect">
</select>
</div>
<button type="submit" class="btn btn-primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Any call to the blockchain is async(returns a promise). You need to either handle the promise with a .then() or you can use async await. Basically anything chained after electionInstance is async. For example:
electionInstance.candidatesCount();
electionInstance.cand_party
electionInstance.voters

MVC - What can I do if I do not want my Email field display error when regular expression validation fails?

I'm creating an MVC page that uses Kendo validation.
I have the following Model:
public class ForgotPasswordModel
{
[Required(ErrorMessage = " ")]
public string UserName { get; set; }
[Required(ErrorMessage = " ")]
[EmailAddress(ErrorMessage = " ")]
public string Email { get; set; }
public string PhoneNumber { get; set; }
[Required(ErrorMessage = " ")]
public string Code { get; set; }
}
I do not want my view to show Error Message for the Email field. I want it to show only exclamation sign when validation fails.
Currently I have the following code in my View:
#model Site.Models.ForgotPasswordModel
#{
ViewBag.Title = "Forgot Password";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/kendo/kendo.common-material.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.custom.css" rel="stylesheet" />
<link href="~/Content/kendo/custom.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<style>
input[type=text]::-ms-clear {
display: none;
}
input[type=password]::-ms-reveal {
display: none;
}
.errMsg {
font-weight: bolder;
color: red;
}
span#UserName_validationMessage, span#Email_validationMessage,span#Code_validationMessage {
display: inline-block;
width: 160px;
text-align: left;
border: 0;
padding: 0;
margin: -20px;
background: none;
box-shadow: none;
color: red;
}
.k-invalid-msg {
display: none;
}
</style>
</head>
<body>
<div>
</div>
<div style="margin-top: 20px;">
<div style="margin: 0 auto; width: 940px; height: 409px; background-image: url('../../Content/images/finance-globe.jpg');"/>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ForgotPasswordForm" }))
{
<div style="margin: 0 auto; margin-top: 20px;">
<table id="ForgotPassword" style="margin: 0" auto;">
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.UserName, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "username" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Email, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "email" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.PhoneNumber, new { htmlAttributes = new { #class = "form-control k-textbox", placeholder = "phone number" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Code, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "code" } })</td>
</tr>
</table>
</div>
}
</div>
</body>
</html>
<script>
$(document).ready(function () {
$("#ForgotPasswordForm").kendoValidator();
});
</script>
The Model and View produce the following:
enter image description here
I do not want "Email is not valid" message to be displayed in case of regular expression validation fails.
I just need an exclamation sign.
How can I do that?
For your email field you can try adding data-email-msg attribute, which is way to customize the validation message for wrong email field value.
For ex: If you want to display a blank message for wrong value for email id you can do something like:
<input type="email" name="email" id="email" name="email" data-email-msg="">
And if you want to customize the required field validation message too, then you can add an another attribute data-required-msg as below:
<input type="email" name="email" id="email" name="email" data-email-msg="" data-required-msg="">

Replacing values in kendo grid

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#"}

Google chart, visulization controlle values

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>

google chart get selected value

I am trying to get the selected value of a Google Table Chart. When the chart content is not filtered using the string filter, it returns the index of the selected row according to the DataTable, but when it is filtered using the string filter, it doesn't returns the correct issue.
To replicate the issue please do the following code
1. Run the below code
Select Aaron in the table. A message box will display its index as 5.
Type letter 'A' in the string filter. Now select the Aaron, it will return 0 which is a bug.
It should return the index of the row in the data table for 'Aaron' which is 5
<!DOCTYPE html>
<html>
<head>
<title>Google Developers</title>
<link rel="stylesheet" type="text/css" href="/_static/07491c0cdc/css/screen-docs.css" />
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400" type="text/css">
<script src="/_static/07491c0cdc/js/prettify-bundle.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script id="jqueryui" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" defer async></script>
<script src="http://www.google.com/jsapi?key=AIzaSyCZfHRnq7tigC-COeQRmoa9Cxr0vbrK6xw"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/_static/07491c0cdc/js/framebox.js"></script>
</head>
<body class="docs slim framebox_body">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="stringFilter_dashboard_div" style="border: 1px solid #ccc">
<div id="stringFilter_control_div" style="padding-left: 2em"></div>
<div id="stringFilter_chart_div"></div>
</div>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart', 'table', 'gauge', 'controls']});
google.setOnLoadCallback(apiLoaded);
function apiLoaded() {
drawStringFilter();
}
function drawStringFilter() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('stringFilter_dashboard_div'));
var control = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'stringFilter_control_div',
'options': {
'filterColumnIndex': 0
}
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'stringFilter_chart_div',
'options': {'height': '25em', 'width': '20em'}
});
google.visualization.events.addListener(chart,'select',tableSelectHandler);
function tableSelectHandler(){
var selectedItem = chart.getChart().getSelection()[0];
alert(selectedItem.row);
}
var data = google.visualization.arrayToDataTable([
['Name', 'Age'],
['Michael' , 12],
['Elisa', 20],
['Robert', 7],
['John', 54],
['Jessica', 22],
['Aaron', 3],
['Margareth', 42],
['Miranda', 33]
]);
dashboard.bind(control, chart);
dashboard.draw(data);
}
</script>
<script>
devsite.github.Link.convertAnchors();
window.prettyPrint();
</script>
</body>
</html>
This should work:
function tableSelectHandler(e){
var selectedItem = chart.getChart().getSelection()[0];
var true_selected = chart.getDataTable().getTableRowIndex(selectedItem.row)
alert(true_selected);
}
getTableRowIndex traces the row back to the datatable
Expanding on juvian's answer, you should test the selection length before trying to access any elements in the array, as the array may be empty (or contain multiple elements if more than one row is selected):
function tableSelectHandler(e){
var selection = chart.getChart().getSelection();
var dt = chart.getDataTable();
for (var i = 0; i < selection.length; i++) {
// colIndex is the index of the column you want to get data from
var value = dt.getValue(selection.row, colIndex);
}
}