Import Excel file to a table of HTML page - javascript

I have a simple Excel file in my computer at "D:/Book1.xls". I want to import it to make a table and append the table to a div tag in my HTML page.
Would you modify my code below?
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style type="text/css">
</style>
<script src='http://alasql.org/console/alasql.min.js'></script>
<script src='http://alasql.org/console/xlsx.core.min.js'></script>
<script src="./libs/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alasql('select * into html("#res",{headers:true}) \
from xlsx("d:/Book1.xls",\
{headers:true})');
alert("end of function")
});
</script>
</head>
<body>
<div id="res">res</div>
</body>
</html>

The problem is you are trying to get access of file directly from web page which is not possible. You cannot access any file outside of you browser. For that you have to select the input element of html and after getting the file data you can store it to javascript variable.
<script src="alasql.min.js"></script>
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
console.log(data);
// You can data to div also.
});
}
</script>

Scripts
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.lob.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collections.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_text.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_io.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_ui.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collectionsextended.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_threading.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_web.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.xml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_openxml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_serialization_openxml.js"></script>
JS
$(function () {
$("#input").on("change", function () {
var excelFile,
fileReader = new FileReader();
$("#result").hide();
fileReader.onload = function (e) {
var buffer = new Uint8Array(fileReader.result);
$.ig.excel.Workbook.load(buffer, function (workbook) {
var column, row, newRow, cellValue, columnIndex, i,
worksheet = workbook.worksheets(0),
columnsNumber = 0,
gridColumns = [],
data = [],
worksheetRowsCount;
// Both the columns and rows in the worksheet are lazily created and because of this most of the time worksheet.columns().count() will return 0
// So to get the number of columns we read the values in the first row and count. When value is null we stop counting columns:
while (worksheet.rows(0).getCellValue(columnsNumber)) {
columnsNumber++;
}
// Iterating through cells in first row and use the cell text as key and header text for the grid columns
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
column = worksheet.rows(0).getCellText(columnIndex);
gridColumns.push({ headerText: column, key: column });
}
// We start iterating from 1, because we already read the first row to build the gridColumns array above
// We use each cell value and add it to json array, which will be used as dataSource for the grid
for (i = 1, worksheetRowsCount = worksheet.rows().count(); i < worksheetRowsCount; i++) {
newRow = {};
row = worksheet.rows(i);
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
cellValue = row.getCellText(columnIndex);
newRow[gridColumns[columnIndex].key] = cellValue;
}
data.push(newRow);
}
// we can also skip passing the gridColumns use autoGenerateColumns = true, or modify the gridColumns array
createGrid(data, gridColumns);
}, function (error) {
$("#result").text("The excel file is corrupted.");
$("#result").show(1000);
});
}
if (this.files.length > 0) {
excelFile = this.files[0];
if (excelFile.type === "application/vnd.ms-excel" || excelFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || (excelFile.type === "" && (excelFile.name.endsWith("xls") || excelFile.name.endsWith("xlsx")))) {
fileReader.readAsArrayBuffer(excelFile);
} else {
$("#result").text("The format of the file you have selected is not supported. Please select a valid Excel file ('.xls, *.xlsx').");
$("#result").show(1000);
}
}
})
});
function createGrid(data, gridColumns) {
if ($("#grid1").data("igGrid") !== undefined) {
$("#grid1").igGrid("destroy");
}
$("#grid1").igGrid({
columns: gridColumns,
autoGenerateColumns: true,
dataSource: data,
width: "100%",
});
}
HTML
<input type="file" id="input" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<div id="result"></div>
<table id="grid1"></table>

Related

Save dynamically created table content in excel file using SheetJS

I add rows into html table dynamically and I want to save the table content into xlsx file using SheetJs. The generated file is empty. Is somehow possible to do this in this case when table content was added this way?
I also tried to add the rows rigth before creating the xlsx file..
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4=" crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.3/xlsx.full.min.js">
</script>
<p>Click the button to add a new row at the first position of the
table and then add cells and content</p>
<table id="myTable">
<TR>
</TR>
</table>
<button type="button" id="first" onclick="First('myTable')">Principal</button>
<button id="button-a">Create Excel</button>
<script>
function First(tableID) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>first</tr>";
}
</script>
<script>
var wb = XLSX.utils.table_to_book(document.getElementById('myTable'), { sheet: "Sheet JS" });
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
$("#button-a").click(function () {
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 'test.xlsx');
});
</script>
</body>
</html>
Issues
text inside tr instead of td in dynamic content. This results in the table structure like below.
XLSX.utils.table_to_book called before table content created.
Working Demo
https://jsfiddle.net/aswinkumar863/95zsfg64/1/

An array can't be used in datatables

I have tried to make a table by using datatables with an array, but somehow it doesn't show the table on my html file.
The array is defined in my gs file as you can see in the code below.
It's a simple work but I'm still not sure what it went wrong.
var ssId = 'xxxxxxxxxxxxx';
var ss = SpreadsheetApp.openById(ssId);
var indexPage_sheetName = 'xxxxxxxx';
var valuesFromIndexPage = ss.getSheetByName(indexPage_sheetName).getDataRange().getValues();//array of 850rows×15cols
valuesFromIndexPage.shift();
function getData() {
$(document).ready(function(){
$("#foo-table").DataTable({
data: valuesFromIndexPage
});
});
}
<html>
<head>
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</head>
</html>
#ZektorH Here's the console log of running my code.
userCodeAppPanel:9 Uncaught TypeError: Cannot read property 'slice' of null
at initializeTable (userCodeAppPanel:9)
at af (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:67)
at 4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:10
at ng.J (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:94)
at Hd (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:42)
at Dd (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:43)
at Bd.b (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:39)
I looked again at my data and I found out the data became null on console.log(but it has data when I see it on Logger.log).
I'm posting what I did and got below.
function getData() {
Logger.log(valuesFromIndexPage); //the array is in valuesFromIndexPage
return valuesFromIndexPage;
}
function initializeTable(data) {
console.log(data); //it returns null here...
var aDataSet = data.slice(1);
The log from Logger.log
[19-10-31 09:47:00:116 JST] [[ID, 案件名, .......
#ZektorH These're the whole codes without data.
code.gs
var ssId = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var ss = SpreadsheetApp.openById(ssId);
var indexPage_sheetName = 'xxxxxxxxxxxxxx';
var valuesFromIndexPage = ss.getSheetByName(indexPage_sheetName).getDataRange().getValues();
function createSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('index').setTitle('My custom sidebar').setWidth(300))
}
function getData() {
return valuesFromIndexPage;
}
function doGet(e) {
return HtmlService.createTemplateFromFile('index').evaluate().setTitle('title');
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
console.log("ready!");
google.script.run.withSuccessHandler(initializeTable).getData(); //calls the getData funciton from Apps Script and returns the results to the initializeTable function
});
function initializeTable(data) {
console.log(data)
var aDataSet = data.slice(1); // all except header
var head = []; // headers
data[0].forEach(function(e) {
head.push({
'sTitle': e
});
});
$('#foo-table').dataTable({
"aaData": aDataSet,
"aoColumns": head
});
}
</script>
</head>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</html>
Chage with columns of of key in dataTable for table headers and chage $("#foo-table").DataTable at $("#foo-table").dataTable
var valuesFromIndexPage=[{"free-text-c1":"free-text-r1","c2":"r1","c3":"r1","c4":"r1","c5":"r1","c6":"r1","c7":"r1","c8":"r1","c9":"free-text-r1","c10":"free-text-r1"},{"free-text-c1":"free-text-r2","c2":"r2","c3":"r2","c4":"r2","c5":"r2","c6":"r2","c7":"r2","c8":"r2","c9":"free-text-r2","c10":"free-text-r2"}];
valuesFromIndexPage.shift();
function getData() {
$(document).ready(function(){
$("#foo-table").dataTable({
destroy: true,
scrollX: true,
data: valuesFromIndexPage,
columns: _.keys(valuesFromIndexPage[0]).map((key) => { return { "title": key, "data": key } })
});
});
}
getData()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<html>
<head>
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</head>
</html>
Assuming you are using it on a sidebar, I was able to get it to work like this:
Apps Script
function createSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('sidebar').setTitle('My custom sidebar').setWidth(300))
}
function getData() {
return SpreadsheetApp.getActiveSheet().getDataRange().getValues();
}
HTML Page
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
console.log("ready!");
google.script.run.withSuccessHandler(initializeTable).getData(); //calls the getData funciton from Apps Script and returns the results to the initializeTable function
});
function initializeTable(data) {
var aDataSet = data.slice(1); // all except header
var head = []; // headers
data[0].forEach(function(e) {
head.push({
'sTitle': e
});
});
$('#foo-table').dataTable({
"aaData": aDataSet,
"aoColumns": head
});
}
</script>
</head>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</html>
Hope this helps!

JavaScript functions are not interpreted when using PivotTable.js

I have integrated PivotTable.js on my web application. The pivot table is shown normally but in some first columns and rows, functions are written and it is not interpreted (See the screenshot) This is an example of a function written:
function each(iterator, context) {
var index = 0;
try {
this._each(function(value) {
iterator.call(context, value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
}
These are screenshots taken from the result:
pivot_table
Pivot table2
This is my code:
<script type="text/javascript" src="./jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui.min.js"></script>
<script type="text/javascript" src="./jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="./pivot.min.js"></script>
<script type="text/javascript" src="./tips_data.min.js"></script>
<link rel="stylesheet" href="./pivot.min.css">
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$("#output").pivotUI(
$.pivotUtilities.tipsData, {
rows: ["sex", "smoker"],
cols: ["day", "time"],
vals: ["tip", "total_bill"],
aggregatorName: "Sum over Sum",
rendererName: "Heatmap"
});
});
</script>
<div id="output"></div>
THe issue is referenced officially here: https://github.com/nicolaskruchten/pivottable/issues/708
As i understand, no out-of-the-box solution yet.

Getting the Value from an editable row

I am working on an application where I need to update the the table cell value So I make that table column editable as below.
I am getting these values from the stackMob database(cloud) .Now I want to Update this Device-nickname(editable table column) from the front-end as from the picture. You can see I am getting the Device-nickname as Undefined. So i want to put the name as I want (as I put alpesh for 352700051252111) .Now when editing is done I means when I complete the editing for first row then I want to call a function which will update the Device-nickname for the correspondence IMEI .
For printing and growing the list I used:
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div contenteditable >"+array[i].device_nickname+"</div></td><tr>");
}
Now My question is:
How can I call a function to update the values when the editing is done for each row. and How can I get the IMEI of that in which editing got done and i want to get also the value after editing of Device-nickname
thanks in advance !!!
full code is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dashboard</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.8.0-bundled-min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/dark-hive/jquery-ui.css" />
<!-- <link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/redmond/jquery-ui.css" />-->
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="style/js/bootstrap.js"></script>
<script type="text/javascript" src="path_to/jquery.js"></script>
<script type="text/javascript" src="path_to/jquery.simplePagination.js"></script>
<link type="text/css" rel="stylesheet" href="path_to/simplePagination.css"/>
<link type="text/css" rel="stylesheet" href="style/css/bootstrap.css"></link>
<script type="text/javascript">
/* <![CDATA[ */
// Initialize StackMob object
// Copy your init data from here: https://dashboard.stackmob.com/sdks/js/config
// Your other app information is here: https://dashboard.stackmob.com/settings
StackMob.init({
appName: "swara_sangam",
clientSubdomain: ".........",
publicKey: "....",
apiVersion: 0
});
/* ]]> */
</script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function() {
result();
function result() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({organization_id:'1' });
var q = new StackMob.Collection.Query();
//q.lt('age', 50)..orderAsc('username');
q.setRange(0,15).orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
// if(array[i].org_img == localStorage.getItem("stackmob.oauth2.user"))
//alert(array[i].org_img);
//$('#last_mod_date').html(array[0].lastmoddate);
//alert(val);
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td ><div class="device-name" contenteditable>"+array[i].device_nickname+"</div></td><td>"+array[i].device_org+"</td><td>"+ new Date(array[i].lastmoddate)+"</td><tr>");
//alert("save");
//$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
alert("save");
//end if condition
} // end for loop
$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
} //end success
}); // end imagesearch schema query
} // end result function
setInterval(check_newentry,1000);
function check_newentry() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({ });
var q = new StackMob.Collection.Query();
q.orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
// alert(lastmod_date_old +"..."+ lastmod_date);
if(lastmod_date_old < lastmod_date)
{
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
var counter=0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td>"+array[i].device_nickname+"</td><td>"+array[i].device_org+"</td><td>"+new Date(array[i].lastmoddate)+"</td><tr>");
//------------------------------------------- end device schema code
counter++;
exit();
}
}
}
});
}
});
</script>
</head>
<body>
<div class="modal-body" style=''>
<table class="data table-bordered table table-striped" id="ui" >
<tr style="background-color:blue;color:white;"><td width="25%">Device-imei</td><td>Device-Model</td><td>device-nickname</td><td>Device-org</td><td>Time</td></tr>
</table>
</div>
<!--<div id="last_mod_date" value=""></div>
<div id="latlng" value=""></div> -->
</script>
</body>
</html>
$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
See http://jsfiddle.net/Jke9J/3/
To get other data you can assign classes for each column, get closest tr after data was changed, and find data by these classes inside found tr
Edit:
See http://jsfiddle.net/Jke9J/7/
SCRIPT:
var editable = document.querySelectorAll('div[contentEditable]');
for (var i=0, len = editable.length; i<len; i++){
editable[i].setAttribute('data-orig',editable[i].innerHTML);
editable[i].onblur = function(){
if (this.innerHTML == this.getAttribute('data-orig')) {
// no change
}
else {
// change has happened, store new value
this.setAttribute('data-orig',this.innerHTML);
}
};
}
Copied from onChange event with contenteditable
You can simplify the above code like
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
}
$(document).on('blur','.divEditable',function(){
if($(this).html()!=$(this).data('orig'))
// innnerHTML is changed then reassign the data-orig attr
{
$(this).data('orig',$(this).html());
// code to get closest imei for that row
imei=$(this).closest('tr').find('td:first-child').html();
console.log(imei);// to test
}
});

How do you style a dojox.grid.DataGrid row?

I have the following example code (you can cut'n'paste it if you want):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"
djConfig="parseOnLoad:true"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/tundra/tundra.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/Grid.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/claroGrid.css" />
<script>
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Button");
function init() {
var lData = {
items: [
{"position":"1","band":"Black Dyke","conductor":"Nick Childs"},
{"position":"2","band":"Carlton Main","conductor":"Philip McCann"},
{"position":"3","band":"Grimethorpe","conductor": "Allan Withington"},
{"position":"4","band":"Brighouse and Rastrick","conductor": "David King"},
{"position":"5","band":"Rothwell Temperance","conductor":"David Roberts"},
],
identifier: "position"
};
var dataStore = new dojo.data.ItemFileReadStore({data:lData});
var grid = dijit.byId("theGrid");
grid.setStore(dataStore);
dojo.connect(dijit.byId("theGrid"), 'onStyleRow', this, function (row) {
var theGrid = dijit.byId("theGrid")
var item = theGrid.getItem(row.index);
if(item){
var type = dataStore.getValue(item, "band", null);
if(type == "Rothwell Temperance"){
row.customStyles += "color:red;";
}
}
theGrid.focus.styleRow(row);
theGrid.edit.styleRow(row);
});
}
var plugins = {
filter: {
itemsName: 'songs',
closeFilterbarButton: true,
ruleCount: 8
}
};
dojo.ready(init);
function filterGrid() {
dijit.byId("theGrid").filter({band: dijit.byId('filterText').get('value')+'*'});
console.log(dijit.byId('filterText').get('value')+'*');
}
function resetFilter() {
dijit.byId("theGrid").filter({band: '*'});
dijit.byId('filterText').set('value','');
}
</script>
</head>
<body class="claro">
<input dojoType="dijit.form.TextBox" id="filterText" type="text" onkeyup="filterGrid()">
<button dojoType="dijit.form.Button" onclick="resetFilter()">Clear</button><br><br>
<table dojoType="dojox.grid.DataGrid" id="theGrid" autoHeight="auto" autoWidth="auto" plugins="plugins">
<thead>
<tr>
<th field="position" width="200px">Position</th>
<th field="band" width="200px">Band</th>
<th field="conductor" width="200px">Conductor</th>
</tr>
</thead>
</table>
</body>
</html>
The onStyleRow only gets fired when I click a row. Is there any way to have a button format rows based on their content? Either by having classes assigned to rows at creation time and then change the class values or loop through the rows and directly changing the style element of each based on it's contents.
EDIT
I have also tried creating the grid programmatically. While when created this way it does fire the onStyleRow at creation time it does not provide the same level of hightlighting the other method does.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"
djConfig="parseOnLoad:true"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/tundra/tundra.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/Grid.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/claroGrid.css" />
<style>
#grid {
height: 20em;
}
</style>
<script>dojoConfig = {async: true, parseOnLoad: false}</script>
<script>
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Button");
function init() {
var lData = {
items: [
{"position":"1","music":"Opera","band":"Black Dyke","conductor":"Nick Childs"},
{"position":"2","music":"Opera","band":"Carlton Main","conductor":"Philip McCann"},
{"position":"3","music":"Classical","band":"Grimethorpe","conductor": "Allan Withington"},
{"position":"4","music":"Classical","band":"Brighouse and Rastrick","conductor": "David King"},
{"position":"5","music":"Opera","band":"Rothwell Temperance","conductor":"David Roberts"},
],
identifier: "position"
};
var dataStore = new dojo.data.ItemFileReadStore({data:lData});
var layout = [[
{'name':'Position','field':'position','width':'50px'},
{'name':'Music Type','field':'music','width':'150px'},
{'name':'Band','field':'band','width':'200px'},
{'name':'Conductor','field':'conductor','width':'200px'}
]];
var grid = new dojox.grid.DataGrid({
id: 'grid',
store: dataStore,
structure: layout,
rowSelector: false,
selectionMode: 'extended',
onStyleRow: function(row) {
var item = this.getItem(row.index);
if(item){
var type = this.store.getValue(item, "band", null);
if(type == "Rothwell Temperance"){
row.customStyles += "color:red;";
}
}
}
});
grid.placeAt("gridDiv");
grid.startup();
}
var plugins = {
filter: {
itemsName: 'songs',
closeFilterbarButton: true,
ruleCount: 8
}
};
dojo.ready(init);
function filterGrid() {
dijit.byId("grid").filter({band: dijit.byId('filterText').get('value')+'*'});
console.log(dijit.byId('filterText').get('value')+'*');
}
function resetFilter() {
dijit.byId("grid").filter({band: '*'});
dijit.byId('filterText').set('value','');
}
</script>
</head>
<body class="claro">
<input dojoType="dijit.form.TextBox" id="filterText" type="text" onkeyup="filterGrid()">
<button dojoType="dijit.form.Button" onclick="resetFilter()">Clear</button><br><br>
<div id="gridDiv"></div>
</body>
</html>
Method 1 (doesn't format when grid is created, nice highlighting)
Method 2 (formats when grid created, no row highlighting)
A simple re-ordering of the init() function makes sure the onStyleRow function is bound before the data is added to the grid works.
function init() {
var lData = {
items: [
{"position":"1","band":"Black Dyke","conductor":"Nick Childs"},
{"position":"2","band":"Carlton Main","conductor":"Philip McCann"},
{"position":"3","band":"Grimethorpe","conductor": "Allan Withington"},
{"position":"4","band":"Brighouse and Rastrick","conductor": "David King"},
{"position":"5","band":"Rothwell Temperance","conductor":"David Roberts"},
],
identifier: "position"
};
var dataStore = new dojo.data.ItemFileReadStore({data:lData});
var grid = dijit.byId("theGrid");
dojo.connect(grid, 'onStyleRow', this, function (row) {
var item = grid.getItem(row.index);
if(item){
var type = dataStore.getValue(item, "band", null);
if(type == "Rothwell Temperance"){
row.customStyles += "color:red;";
//row.customClasses += " dismissed";
}
}
//theGrid.focus.styleRow(row);
//theGrid.edit.styleRow(row);
});
grid.setStore(dataStore);
}
Have you tried any of the following:
Style Dojox Grid Row depending on data
dojox DataGrid onStyleRow works first time, then not again
dojox.grid.DataGrid - onStyleRow needs update? (dojo 1.2.0)
You can also use Firebug to see if rows are getting assigned an ID and then change background of each row using onStyleRow.

Categories