ExtJS 4.2 export grid data to downloadable CSV file - javascript

I want to create a download button in my EXT JS panel which when click download/exports EXTJS grid into downloadable CSV file.
PS: I think we can use store data or the JSON from which i am filling data in grid store to populate data into CSV file
I have tried Ext.ux.CSVExporter but i wasn't able to use it successfully.
My current code is :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title id='title'>HTML Page setup Tutorial</title>
<link rel="stylesheet" type="text/css" href="ext-all.css" />
<script type="text/javascript" src="ext-all.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>
<script type="text/javascript" src="Formatter.js"></script>
<script type="text/javascript" src="CSVFormatter/CSVFormatter.js"></script>
<script type="text/javascript" src="ExcelFormatter/Cell.js"></script>
<script type="text/javascript" src="ExcelFormatter/Style.js"></script>
<script type="text/javascript" src="ExcelFormatter/Workbook.js"></script>
<script type="text/javascript" src="ExcelFormatter/Worksheet.js"></script>
<script type="text/javascript" src="ExcelFormatter/ExcelFormatter.js"></script>
<script type="text/javascript" src="Exporter.js"></script>
<script type="text/javascript" src="ExporterButton.js"></script>
<script type="text/javascript">
Ext.define('Ext.ux.ProgressBarPager', {
requires: ['Ext.ProgressBar'],
/**
* #cfg {Number} width
* <p>The default progress bar width. Default is 225.</p>
*/
width : 225,
/**
* #cfg {String} defaultText
* <p>The text to display while the store is loading. Default is 'Loading...'</p>
*/
defaultText : 'Loading...',
/**
* #cfg {Object} defaultAnimCfg
* <p>A {#link Ext.fx.Anim Ext.fx.Anim} configuration object.</p>
*/
defaultAnimCfg : {
duration: 1000,
easing: 'bounceOut'
},
/**
* Creates new ProgressBarPager.
* #param {Object} config Configuration options
*/
constructor : function(config) {
if (config) {
Ext.apply(this, config);
}
},
//public
init : function (parent) {
var displayItem;
if (parent.displayInfo) {
this.parent = parent;
displayItem = parent.child("#displayItem");
if (displayItem) {
parent.remove(displayItem, true);
}
this.progressBar = Ext.create('Ext.ProgressBar', {
text : this.defaultText,
width : this.width,
animate : this.defaultAnimCfg,
style: {
cursor: 'pointer'
},
listeners: {
el: {
scope: this,
click: this.handleProgressBarClick
}
}
});
parent.displayItem = this.progressBar;
parent.add(parent.displayItem);
Ext.apply(parent, this.parentOverrides);
}
},
// private
// This method handles the click for the progress bar
handleProgressBarClick : function(e){
var parent = this.parent,
displayItem = parent.displayItem,
box = this.progressBar.getBox(),
xy = e.getXY(),
position = xy[0]- box.x,
pages = Math.ceil(parent.store.getTotalCount() / parent.pageSize),
newPage = Math.max(Math.ceil(position / (displayItem.width / pages)), 1);
parent.store.loadPage(newPage);
},
// private, overriddes
parentOverrides : {
// private
// This method updates the information via the progress bar.
updateInfo : function(){
if(this.displayItem){
var count = this.store.getCount(),
pageData = this.getPageData(),
message = count === 0 ?
this.emptyMsg :
Ext.String.format(
this.displayMsg,
pageData.fromRecord, pageData.toRecord, this.store.getTotalCount()
),
percentage = pageData.pageCount > 0 ? (pageData.currentPage / pageData.pageCount) : 0;
this.displayItem.updateProgress(percentage, message, this.animate || this.defaultAnimConfig);
}
}
}
});
Ext.onReady(function() {
var field = [];
var columnList = [];
var counter = {
"levels":
[{
"name": "class",
"samples": [{
"name": "1660SH_3",
"features": [{
"count": 8,
"name": "Bacteroidia"
}, {
"count": 9,
"name": "Bacteroidiaa"
},
{
"count": 10,
"name": "Bacteroidiab"
},
{
"count": 11,
"name": "Bacteroidiac"
}]
}, {
"name": "1660SH_4",
"features": [{
"count": 5,
"name": "Bacteroidia"
}, {
"count": 6,
"name": "Bacteroidiaa"
},
{
"count": 7,
"name": "Bacteroidiab"
},
{
"count": 8,
"name": "Bacteroidiac"
}]
}]
}, ]
};
columnList.push({
header: "Sample v/s Feature",
dataIndex: "Sample v/s Feature",
width: 0.1 * Ext.getBody().getViewSize().width,
columnLines: true,
locked: true
});
field.push("Sample v/s Feature");
for (var p = 0; p < Object.keys(counter.levels[0].samples).length; p++) {
columnList.push({
header: counter.levels[0].samples[p].name,
dataIndex: counter.levels[0].samples[p].name,
flex: 1,
columnLines: true
});
field.push(counter.levels[0].samples[p].name);
}
if (counter.levels[0].name == 'class') {
var mydata=[];
for (var p = 0; p < Object.keys(counter.levels[0].samples[0].features).length; p++)
{
var s = [];
s["Sample v/s Feature"] = '<b>' + counter.levels[0].samples[0].features[p].name + '</b>';
for (var j = 0; j < Object.keys(counter.levels[0].samples).length; j++)
{
s[counter.levels[0].samples[j].name] = counter.levels[0].samples[j].features[p].count;
}
mydata.push(s);
}
var store = Ext.create('Ext.data.ArrayStore', {
autoLoad: false,
pageSize : 2,
fields: field,
data: {
count:mydata.length,
data:mydata
},
proxy:{
type:"memory",
enablePaging: true,
data:mydata,
reader: {
type: 'json',
root: 'data',
}
}
});
store.load({
params: {
// specify params for the first page load if using paging
start: 0,
limit: 2,
}
});
var classTable = Ext.create('Ext.grid.Panel', {
style: 'border: solid Blue 1px',
id: 'family',
renderTo: Ext.getBody(),
store: store,
requires: [
'Ext.ux.exporter.Exporter'
],
columns: columnList,
columnLines: true,
width: Ext.getBody().getViewSize().width,
height: Ext.getBody().getViewSize().height,
bbar: {
xtype: 'pagingtoolbar',
pageSize: 2,
store: store,
displayInfo: true,
plugins: new Ext.ux.ProgressBarPager()
},
dockedItems:[
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'exporterbutton',
text: 'export data'
}
]
}
]
});
}
});
</script>
</head>
<body>
</body>
</html>

repository link use this project
here is example how to use it fiddle link
first of all copy repository files to you ext library's ux folder located in ext/src/ux under exporter folder. full path will be ext/src/ux/exporter/[repository_files]
and modify your grid
var classTable = Ext.create('Ext.grid.Panel', {
style: 'border: solid Blue 1px',
id: 'family',
renderTo: Ext.getBody(),
store: store,
requires: [
'Ext.ux.exporter.Exporter'
],
columns: columnList,
columnLines: true,
width: Ext.getBody().getViewSize().width,
height: Ext.getBody().getViewSize().height,
bbar: {
xtype: 'pagingtoolbar',
pageSize: 2,
store: store,
displayInfo: true,
plugins: new Ext.ux.ProgressBarPager()
},
dockedItems:[
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'exporterbutton',
text: 'exrpot data'
}
]
}
]
});

Related

how to run a python file in Typescript file

I have a typescript extension that needs to run a python file. after a file dialog is opened the extension uses exec to run the following command.
python C:\\Users\\schriste\\.vscode\\extensions\\consolidatedExtension\\src\\testingFile.py C:\\EquipVsCode\\5G_ServingCell_Rsrp_Rsrq_Sinr_RSSI_B974_all.isf
I thought exec would work since ive tired exec using the windows command dir and it worked just fine.
all I need is the right function to run the command shown above. has anyone done this? it seems like such a simple and common task but im having so much difficulty finding information on how this can be done.
below is the code from extension.ts
perhaps someone has information on how the following work for what I am trying to accomplish but I have not found a way for these to work as of right now: execFile spawn
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { open } from 'fs';
import * as path from 'path';
import { json } from 'stream/consumers';
const { ChildProcess, exec } = require('child_process');
const { execFile } = require('node:child_process');
const { spawn } = require('node:child_process');
const { stdout, stderr } = require('process');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
//File Dialog
let disposable = vscode.commands.registerCommand('consolidatedExtension.openFile', function () {
const options = {
canSelectMany: false,
openLabel: 'Open'
};
vscode.window.showOpenDialog(options).then(fileUri => {
if (fileUri && fileUri[0]) {
console.log('Selected file: ' + fileUri[0].fsPath);
let cmd = `python C:\\Users\\schriste\\.vscode\\extensions\\consolidatedExtension\\src\\testingFile.py` + ` ` + fileUri[0].fsPath
exec(cmd2, (...args: any[])=>{
console.log(args);
});
}
});
});
//open graphView
let openWebview = vscode.commands.registerCommand('consolidatedExtension.openWebview', () => {
const panel = vscode.window.createWebviewPanel(
'openWebview', // Identifies the type of the webview. Used internally
'Example Page', // Title of the panel displayed to the user
vscode.ViewColumn.One, // Editor column to show the new webview panel in.
{ // Enable scripts in the webview
enableScripts: true //Set this to true if you want to enable Javascript.
});
//get path to json on disk
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, 'src', 'data.json')
);
//get vegaLite js on disk
const JsonDiskPath = vscode.Uri.file(
path.join(context.extensionPath, 'src', 'vegaLiteGraphs.js')
);
//and get the special URI to use with the webview
const jsonSRC = panel.webview.asWebviewUri(onDiskPath);
const jsSRC = panel.webview.asWebviewUri(JsonDiskPath);
panel.webview.html = getWebviewContent(jsonSRC, jsSRC);
});
context.subscriptions.push(openWebview);
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {}
function getWebviewContent(jsonSRC:vscode.Uri, jsSRC:vscode.Uri) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.jsdelivr.net/npm/vega#5.21.0"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite#5.2.0"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed#6.20.2"></script>
</head>
<body>
<script type = "module">
import users from '${jsonSRC}' assert {type: 'json'};
const graphDataContainer = []
let dataPoints = []
for(let i = 0; i < users.length; i += 2)
{
for (let j = 1; j < users[i].length; j++) {
dataPoints.push({
x: users[i][j],
y: users[i + 1][j]
});
}
graphDataContainer.push(dataPoints)
dataPoints = []
}
console.log(graphDataContainer)
window.onload = function() {
let i = 0
var chart1 = new CanvasJS.Chart("chart1", {
animationEnabled: true,
zoomEnabled: true,
theme: "light2",
"title": { "text": "RSRP" },
axisX: {
gridThickness: 0,
tickLength: 0,
lineThickness: 0,
labelFormatter: function(){ return " "; },
crosshair: {
enabled: true,
color: "black",
labelFontColor: "#F8F8F8"
},
//interval: 10,
//intervalType: "millisecond",
//valueFormatString: "##.##.####"
},
axisY: {
crosshair: {
enabled: true,
color: "black",
labelFontColor: "#F8F8F8"
},
title: "Serving Cell RSRP (dBm)",
minimum: -100,
maximum: 0,
interval: 16.67
},
data: [{
type: "line",
//yValueFormatString: "#,### Units",
dataPoints: graphDataContainer[i]
}],
rangeChanged: syncHandler
});
chart1.render();
i++
var rsrqChart = new CanvasJS.Chart("chart2", {
animationEnabled: true,
zoomEnabled: true,
theme: "light2",
axisX: {
valueFormatString:"##:##:##.###",
crosshair: {
enabled: true,
color: "black",
labelFontColor: "#F8F8F8"
},
},
axisY: {
crosshair: {
enabled: true,
color: "black",
labelFontColor: "#F8F8F8"
},
title: "Serving Cell RSRQ",
minimum: -15,
interval: 2.5
},
data: [{
type: "line",
dataPoints: graphDataContainer[i]
}],
rangeChanged: syncHandler
});
rsrqChart.render();
// var chart3 = new CanvasJS.Chart("chartContainer3", {
// animationEnabled: true,
// theme: "light2",
// data: [{
// type: "line",
// dataPoints: sinrPoints
// }]
// });
// chart3.render();
var charts = [chart1, rsrqChart];
function syncHandler(e){
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
if (!chart.options.axisX)
chart.options.axisX = {};
if (!chart.options.axisY)
chart.options.axisY = {};
if (e.trigger === "reset") {
chart.options.axisX.viewportMinimum = chart.options.axisX.viewportMaximum = null;
chart.options.axisY.viewportMinimum = chart.options.axisY.viewportMaximum = null;
chart.render();
} else if (chart !== e.chart) {
chart.options.axisX.viewportMinimum = e.axisX[0].viewportMinimum;
chart.options.axisX.viewportMaximum = e.axisX[0].viewportMaximum;
chart.options.axisY.viewportMinimum = e.axisY[0].viewportMinimum;
chart.options.axisY.viewportMaximum = e.axisY[0].viewportMaximum;
chart.render();
}
}
}
}
</script>
<script type = "module" src = "${jsSRC}"></script>
<div id="chart1" style="height: 370px; width: 100%;"></div>
<div id="chart2" style="height: 370px; width: 100%;"></div>
<div id="vis"></div>
<!-- <div id="chartContainer3" style="height: 370px; width: 100%;"></div> -->
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
</body>
</html>
`;
}

Json data for apexcharts

I have some problems rendering some data from a JSON in my apexchart series.
Here is the example of my chart with the data that I want to be in my JSON, and i don't know how to write it.
var _seed = 42;
Math.random = function() {
_seed = _seed * 16807 % 2147483647;
return (_seed - 1) / 2147483646;
};
var options = {
series: [{
name: "Q",
data: [0, 4800, 9500, null],
},
{
name: "Q - 1",
data: [0, 6500, 12000, 16000]
},{
name: "Q Target",
data: [15500, 15500, 15500, 15500]
},
],
chart: {
height: 350,
type: 'line',
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'straight'
},
title: {
text: 'Clicks',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: [' ', 'Month1', 'Month2', 'Month3'],
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
#chart {
max-width: 450px;
margin: 35px auto;
}
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill#8/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/eligrey-classlist-js-polyfill"></script>
<script src="https://cdn.jsdelivr.net/npm/findindex_polyfill_mdn"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.auto.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>
If someone could give me a hint, is kindly appreciated.
The JSON looks like this , for retrieving data for the apexchart
{
"data_clicks":[
{
"name":"Q",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":2400
},
{
"x":"Month2",
"y":5200
},
{
"x":"Month3",
"y":null
}
]
},
{
"name":"Q - 1",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":1800
},
{
"x":"Month2",
"y":7150
},
{
"x":"Month3",
"y":10200
}
]
},
{
"name":"Q Target",
"data":[
{
"x":" ",
"y":11000
},
{
"x":"Month1",
"y":11000
},
{
"x":"Month2",
"y":11000
},
{
"x":"Month3",
"y":11000
}
]
}
],

Firefox Web Extension bug - Unable to render Highcharts

I believe there's a bug in Firefox addons where Highcharts within web-extensions cannot be rendered.
I'm porting a Chrome extension into Firefox. When you click on the extension icon, the popup window renders some charts using Highcharts dynamically. This works in Chrome & Safari. However, with Firefox, the tabbrowser.xml at line 5828 (shown below) script becomes unresponsive. If the Highcharts are NOT used, the extension loads fine.
Here's the minimal code (from the github link below) to generate simple HighCharts in my extension. I used this to reproduce the issue. https://github.com/bluechips23/FirefoxTesting
Libraries Used:
JQuery: Version 1.12.4 from https://code.jquery.com/jquery-1.12.4.js
Highcharts: version 5.0.10 from http://www.highcharts.com/download
JQuery UI: Version 1.12.1 from https://jqueryui.com/resources/download/jquery-ui-1.12.1.zip
Code from extension
manifest.json
{
"manifest_version": 2,
"name": "AppDebugging",
"description": "Testing app",
"version": "2.0.0.0",
"icons": {
"16": "16.png",
"48": "48.png",
"128": "128.png"
},
"background": {
"scripts": ["browser.js", "eventPage.js"],
"persistent": false
},
"page_action": {
"default_icon": "icon4.png",
"default_popup": "popup.html",
"default_title": "Testing App"
},
"permissions": [
"http://*/*",
"https://*/*",
"tabs"
]
}
2. popup.html
<!doctype html>
<html>
<head>
<title>Test Popup</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
<script src="popup.js"></script>
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/highcharts.js"></script>
</head>
<body>
<div class='header' id="header">
<h1 id="banner">TESTING</h1>
</div>
<div class="bodyContainer" id="bodyId">
<div class="container" id="container-0"></div>
<div class="container" id="container-1"></div>
<div class="container" id="container-2"></div>
</div>
</body>
</html>
3. popup.js
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
browser.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
console.assert(typeof url == 'string', 'tab.url should be a string');
callback(url);
});
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('a[href]').forEach(function (el) {
el.addEventListener('click', function (event) {
event.preventDefault();
browser.tabs.create({
url: event.target.getAttribute('href')
});
});
});
getCurrentTabUrl(function(url) {
generateData();
});
var generateData = function() {
console.debug("inside generate data.....");
var categoryData = new Array();
for(var index = 0; index < 10; index++) {
var category = "Category " + index;
categoryData.push(category);
}
for(var index = 0; index < 3; index++) {
var positiveData = getRandomArray();
var negativeData = getRandomArray();
var neutralData = getRandomArray();
var containerID = "container-" + index;
console.debug("Container id : " + containerID);
createChart(name, categoryData, positiveData, negativeData, neutralData, containerID);
}
};
var getRandomNumber = function(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var getRandomArray = function() {
var min = 0;
var max = 50;
var myArray = new Array();
for(var index = 0; index < 10; index++) {
var random = getRandomNumber(min, max);
myArray.push(parseInt(random));
}
return myArray;
};
var createChart = function(name, categoryData, positiveData,
negativeData, neutralData, container) {
var titleString = "Chart " + name;
var subTitleString = "This is a test";
Highcharts.chart(container, {
chart: {
type: 'bar',
style: {
color: '#333'
},
backgroundColor: "#f2f2f2"
},
title: {
text: titleString,
style: {
color: '#333'
}
},
subtitle: {
text: subTitleString,
style: {
color: '#333',
fontSize: "15px"
}
},
xAxis: {
categories: categoryData,
labels: {
style: {
fontSize: "12px"
}
},
},
yAxis: {
min: 0,
title: {
text: 'Values',
align: 'high',
style: {
fontSize: '18px',
}
},
labels: {
overflow: 'justify',
style: {
fontSize: '14px',
}
},
tickPositioner: function () {
var positions = [],
tick = Math.floor(this.dataMin),
increment = Math.ceil((this.dataMax - this.dataMin) / 6);
if (this.dataMax !== null && this.dataMin !== null) {
for (tick; tick - increment <= this.dataMax; tick += increment) {
positions.push(tick);
}
}
return positions;
},
gridLineWidth: 0,
},
colors: [
'#4be8a1',
'#ed6764',
'#adadad',
],
plotOptions: {
series: {
pointWidth: 5, //width of the column bars irrespective of the chart size
groupPadding: 0.1,
pointPadding: 0
},
column: {
colorByPoint: true
},
},
legend: {
enabled: false
},
credits: {
enabled: false
},
tooltip: {
shadow: true,
useHTML: true,
shared: true,
backgroundColor: '#f2f2f2'
},
series: [{
name: 'Positive',
data: positiveData
}, {
name: 'Negative',
data: negativeData
}, {
name: 'Neutral',
data: neutralData
}]
});
};});
Here's the full error stack on debugger:
Error: Script terminated by timeout at:
handleEvent#chrome://browser/content/tabbrowser.xml:5828:1
_handleDOMChange#chrome://extensions/content/ext-browser-content.js:203:7
tabbrowser.xml:5828:1
NS_ERROR_ILLEGAL_VALUE: Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIMessageSender.sendAsyncMessage] ext-browser-content.js:213
Here's the tabbrowser.xml:5828:
<method name="handleEvent">
<parameter name="aEvent"/>
<body><![CDATA[ // This switch statement throws error.
switch (aEvent.type) {
case "load":
this.updateVisibility();
TabsInTitlebar.init();
break;
case "resize":
if (aEvent.target != window)
break;
TabsInTitlebar.updateAppearance();
....
</method>
Here's the code at ext-browser-content.js:203
_handleDOMChange(detail) {
let doc = content.document;
.... [truncated code]....
// LINE BELOW THROWS ERROR
contentViewer.getContentSizeConstrained(this.maxWidth * ratio,
this.maxHeight * ratio,
w, h);
let width = Math.ceil(w.value / ratio);
let height = Math.ceil(h.value / ratio);
result = {width, height, detail};
}
sendAsyncMessage("Extension:BrowserResized", result);
},
};

Fuelux - how to use repeater

I am trying to use Fuelux repeater for one of my projects but I cant figure out how to populate data using javascript. The examples they have provided use couple of other plugins(Require.js and underscore.js) and I am not familiar with those. Can someone please help me to do this without any other plugins. I removed all require methods in the code but that didnt work either. Please look at this fiddle for what I have so far.
/*!
* JavaScript for Fuel UX's docs - Repeater Examples
* Copyright 2011-2014 ExactTarget, Inc.
* Licensed under the Creative Commons Attribution 3.0 Unported License. For
* details, see http://creativecommons.org/licenses/by/3.0/.
*/
define function(require){
// var $ = require('jquery');
// var _ = require('underscore');
var colors = {
bug: '#A8B820',
dark: '#705848',
dragon: '#7038F8',
electric: '#F8D030',
fairy: '#EE99AC',
fighting: '#C03028',
fire: '#F08030',
flying: '#A890F0',
ghost: '#705898',
grass: '#78C850',
ground: '#E0C068',
ice: '#98D8D8',
normal: '#A8A878',
poison: '#A040A0',
psychic: '#F85888',
rock: '#B8A038',
steel: '#B8B8D0',
water: '#6890F0'
};
var columns = [
{
label: 'Name',
property: 'name',
sortable: true
},
{
label: 'Id',
property: 'id',
sortable: true
},
{
label: 'Type',
property: 'type',
sortable: true
},
{
label: 'Height (in)',
property: 'height',
sortable: true
},
{
label: 'Weight (lbs)',
property: 'weight',
sortable: true
},
{
label: 'Abilities',
property: 'abilities',
sortable: true
},
{
label: 'Weakness',
property: 'weakness',
sortable: true
}
];
var delays = ['300', '600', '900', '1200'];
var pokemon = [{
"abilities": "Overgrow",
"weight": "15.2",
"weakness": "fire, flying, ice, psychic",
"height": "28.0",
"id": "001",
"name": "Bulbasaur",
"ThumbnailAltText": "Bulbasaur",
"ThumbnailImage": "http://assets2.pokemon.com/assets/cms2/img/pokedex/detail/001.png",
"type": "grass, poison"
},
{
"abilities": "Overgrow",
"weight": "28.7",
"weakness": "fire, flying, ice, psychic",
"height": "39.0",
"id": "002",
"name": "Ivysaur",
"ThumbnailAltText": "Ivysaur",
"ThumbnailImage": "http://assets3.pokemon.com/assets/cms2/img/pokedex/detail/002.png",
"type": "grass, poison"
},
{
"abilities": "Overgrow, Thick Fat",
"weight": "342.8",
"weakness": "fire, psychic, flying, ice",
"height": "94.0",
"id": "003",
"name": "Venusaur",
"ThumbnailAltText": "Venusaur",
"ThumbnailImage": "http://assets4.pokemon.com/assets/cms2/img/pokedex/detail/003.png",
"type": "grass, poison"
}];
var dataSource, filtering;
// require('bootstrap');
// require('fuelux');
dataSource = function(options, callback){
var items = filtering(options);
var resp = {
count: items.length,
items: [],
page: options.pageIndex,
pages: Math.ceil(items.length/(options.pageSize || 50))
};
var i, items, l;
i = options.pageIndex * (options.pageSize || 50);
l = i + (options.pageSize || 50);
l = (l <= resp.count) ? l : resp.count;
resp.start = i + 1;
resp.end = l;
if(options.view==='list' || options.view==='thumbnail'){
if(options.view==='list'){
resp.columns = columns;
for(i; i<l; i++){
resp.items.push(items[i]);
}
}else{
for(i; i<l; i++){
resp.items.push({
color: colors[items[i].type.split(', ')[0]],
name: items[i].name,
src: items[i].ThumbnailImage
});
}
}
setTimeout(function(){
callback(resp);
}, delays[Math.floor(Math.random() * 4)]);
}
};
filtering = function(options){
var items = $.extend([], pokemon);
var search;
if(options.filter.value!=='all'){
items = _.filter(items, function(item){
return (item.type.search(options.filter.value)>=0);
});
}
if(options.search){
search = options.search.toLowerCase();
items = _.filter(items, function(item){
return (
(item.name.toLowerCase().search(options.search)>=0) ||
(item.id.toLowerCase().search(options.search)>=0) ||
(item.type.toLowerCase().search(options.search)>=0) ||
(item.height.toLowerCase().search(options.search)>=0) ||
(item.weight.toLowerCase().search(options.search)>=0) ||
(item.abilities.toLowerCase().search(options.search)>=0) ||
(item.weakness.toLowerCase().search(options.search)>=0)
);
});
}
if(options.sortProperty){
items = _.sortBy(items, function(item){
if(options.sortProperty==='id' || options.sortProperty==='height' || options.sortProperty==='weight'){
return parseFloat(item[options.sortProperty]);
}else{
return item[options.sortProperty];
}
});
if(options.sortDirection==='desc'){
items.reverse();
}
}
return items;
};
// REPEATER
$('#repeaterIllustration').repeater({
dataSource: dataSource
});
$('#myRepeater').repeater({
dataSource: dataSource
});
$('#myRepeaterList').repeater({
dataSource: dataSource
});
$('#myRepeaterThumbnail').repeater({
dataSource: dataSource,
thumbnail_template: '<div class="thumbnail repeater-thumbnail" style="background: {{color}};"><img height="75" src="{{src}}" width="65"><span>{{name}}</span></div>'
});
}
You seem to be doing everything right.. Only thing you had to do was load jQuery on onLoad and comment out define function(require) statement..
JSFiddle

How to set up jqxListBox of jqxGrid programmatically

I have a jqxGrid with jqxListBox inputs as cells. How can I set the cells' values programmatically by selecting their jqxListBox index?
See a demo here:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm?%28web%29#demos/jqxgrid/customrowcelledit.htm
For a standalone jqxListbox, it can be simply done as
$("#jqxListBox").jqxListBox('selectIndex', 0 );
But how can I do it if it is part of the grid? I need to change cell values after the grid is initialized. Overwriting cell values instead of changing the selected index is not a good solution.
You need to use the "initeditor" callback function of the Column. The same demo is below, but with the jQWidgets ListBox instead of the jQWidgets DropDownList as an editor.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcheckbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxnumberinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxslider.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript" src="generatedata.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var theme = getDemoTheme();
// prepare the data
var data = new Array();
data.push({ "Name": "Population", "Berlin": "3560154", "Boston": "3406829", "London": "8174100" });
data.push({ "Name": "Country", "Berlin": "Germany", "Boston": "United States", "London": "United Kingdom" });
data.push({ "Name": "Capital", "Berlin": "true", "Boston": "false", "London": "true" });
var source =
{
localdata: data,
datatype: "array",
updaterow: function (rowid, rowdata, commit) {
// synchronize with the server - send update command
// call commit with parameter true if the synchronization with the server is successful
// and with parameter false if the synchronization failder.
commit(true);
},
datafields:
[
{ name: 'Name', type: 'string' },
{ name: 'Berlin', type: 'string' },
{ name: 'Boston', type: 'string' },
{ name: 'London', type: 'string' }
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
var createGridEditor = function(row, cellValue, editor, cellText, width, height)
{
// construct the editor.
if (row == 0) {
editor.jqxNumberInput({ decimalDigits: 0, inputMode: 'simple', theme: theme, width: width, height: height, spinButtons: true });
}
else if (row == 1) {
editor.jqxListBox({theme: theme, width: width, height: height, source: ['United States', 'Germany', 'United Kingdom']});
}
else if (row == 2) {
var element = $('<div tabIndex=0 style="position: absolute; top: 50%; left: 50%; margin-top: -7px; margin-left: -10px;"></div>');
editor.append(element);
element.jqxCheckBox({ animationShowDelay: 0, animationHideDelay: 0, width: 16, height: 16, theme: theme });
}
}
var initGridEditor = function (row, cellValue, editor, cellText, width, height) {
// set the editor's current value. The callback is called each time the editor is displayed.
if (row == 0) {
editor.jqxNumberInput({ decimal: parseInt(cellValue)});
}
else if (row == 1) {
editor.jqxListBox('selectItem', cellValue);
}
else if (row == 2) {
var checkBoxHTMLElement = editor.find('div:first');
checkBoxHTMLElement.jqxCheckBox({ checked: cellValue.toString() == "true" });
}
}
var gridEditorValue = function (row, cellValue, editor) {
if (row == 2) {
var checkBoxHTMLElement = editor.find('div:first');
return checkBoxHTMLElement.val();
}
return editor.val();
}
// initialize jqxGrid
$("#jqxgrid").jqxGrid(
{
width: 600,
rowsheight: 60,
autoheight: true,
source: dataAdapter,
editable: true,
theme: theme,
selectionmode: 'singlecell',
columns: [
{
text: 'Name', pinned: true, editable: false, datafield: 'Name', width: 150
},
{
text: 'Boston', columntype: 'custom', datafield: 'Boston', width: 150,
createeditor: createGridEditor, initeditor: initGridEditor, geteditorvalue: gridEditorValue
},
{
text: 'Berlin', columntype: 'custom', datafield: 'Berlin', width: 150,
createeditor: createGridEditor, initeditor: initGridEditor, geteditorvalue: gridEditorValue
},
{
text: 'London', columntype: 'custom', datafield: 'London',
createeditor: createGridEditor, initeditor: initGridEditor, geteditorvalue: gridEditorValue
}
]
});
});
</script>
</head>
<body class='default'>
<div id="jqxgrid"></div>
</body>
</html>
Hope this helps you.

Categories

Resources