I am using table2excel.js for export HTML to Excel and it is working fine. I want to change row or column color as per condition. Is it possible?
<table id="ExcelTable" style="text-align: left;display:none">
<tr class="rpthide">
<td class="Supplier" style="font-size:14px;"></td>
<td class="ContractNo" style="font-size:14px;"></td>
<td class="OrderNo" style="font-size:14px;"></td>
<td class="Article" style="font-size:14px;"></td>
<td class="Ordered" style="font-size:14px;"></td>
<td class="ContainerNo" style="font-size:14px;"></td>
<td class="ETA" style="font-size:14px;"></td>
<td class="Dispatched" style="font-size:14px;"></td>
<td class="AtPort" style="font-size:14px;"></td>
<td class="Arrived" style="font-size:14px;"></td>
</tr>
</table>
$("#ExcelTable").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Yarn Status List",
filename: "Yarn Status List" //do not include extension
});
I suggest you use better tools like as ExcellentExport.js
you can apply any css style to the html table, and they will be exported at the output.
Sample Usage:
<script src="excellentexport.js"></script>
<table id="ExcelTable">
<tr>
<td style="color:red">Column 1</td>
<td style="color:blue">Column 2</td>
<td style="color:green; font-weight:bold">Column 3</td>
</tr>
<tr style="color: purple">
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
</table>
<a download="myFile.xls" href="#" onclick="return ExcellentExport.excel(this, 'ExcelTable', 'Sheet1');">Export to Excel</a>
use span tag in td.
Ex: <td> <span style="color:red">6000</span> </td>
its work fine for me.
make preserveFont:true to use font-size and font-weight
$(function () {
$("#exportexcel").click(function () {
var $table = $('.table2excel');
$table.removeData(); //data is removed, previous when data existed was preventing initialization of table2excel
$table.table2excel({
exclude: ".noExl",
sheetName: "Demo_Report",
filename: "demo_Report",
fileext: ".xls",
preserveFont:true,
});
});
});
yes you can to change color you should use PreserveColor:true option which has given in table2excel github repo and for font-size and font-weight I have make changes in main file below Iam sharing you my table2excel raw code and PreserveFont option is made by me so you can use it .it get you fontsize and font-weight from your table
/*
* jQuery table2excel - v1.1.2
* jQuery plugin to export an .xls file in browser from an HTML table
* https://github.com/rainabba/jquery-table2excel
*
* Made by rainabba
* Under MIT License
*/
//table2excel.js
(function ($, window, document, undefined) {
var pluginName = "table2excel",
defaults = {
exclude: ".noExl",
name: "Table2Excel",
filename: "table2excel",
fileext: ".xls",
exclude_img: true,
exclude_links: true,
exclude_inputs: true,
preserveColors: false
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
//
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var e = this;
var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
e.template = {
head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
sheet: {
head: "<x:ExcelWorksheet><x:Name>",
tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
},
mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
table: {
head: "<table>",
tail: "</table>"
},
foot: "</body></html>"
};
e.tableRows = [];
// Styling variables
var additionalStyles = "";
var compStyle = null;
// get contents of table except for exclude
$(e.element).each(function (i, o) {
var tempRows = "";
$(o).find("tr").not(e.settings.exclude).each(function (i, p) {
// Reset for this row
additionalStyles = "";
// Preserve background and text colors on the row
if (e.settings.preserveColors) {
compStyle = getComputedStyle(p);
additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
}
// Create HTML for Row
tempRows += "<tr style='" + additionalStyles + "'>";
// Loop through each TH and TD
$(p).find("td,th").not(e.settings.exclude).each(function (i, q) { // p did not exist, I corrected
// Reset for this column
additionalStyles = "";
// Preserve background and text colors on the row
if (e.settings.preserveColors) {
compStyle = getComputedStyle(q);
additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
}
if (e.settings.preserveFont) {
compStyle = getComputedStyle(q);
additionalStyles += (compStyle && compStyle.fontSize ? "font-size : " + compStyle.fontSize + ";" : "");
additionalStyles += (compStyle && compStyle.fontWeight ? "font-weight : " + compStyle.fontWeight + ";" : "");
}
var rc = {
rows: $(this).attr("rowspan"),
cols: $(this).attr("colspan"),
flag: $(q).find(e.settings.exclude)
};
if (rc.flag.length > 0) {
tempRows += "<td> </td>"; // exclude it!!
} else {
tempRows += "<td";
if (rc.rows > 0) {
tempRows += " rowspan='" + rc.rows + "' ";
}
if (rc.cols > 0) {
tempRows += " colspan='" + rc.cols + "' ";
}
if (additionalStyles) {
tempRows += " style='" + additionalStyles + "'";
}
tempRows += ">" + $(q).html() + "</td>";
}
});
tempRows += "</tr>";
});
// exclude img tags
if (e.settings.exclude_img) {
tempRows = exclude_img(tempRows);
}
// exclude link tags
if (e.settings.exclude_links) {
tempRows = exclude_links(tempRows);
}
// exclude input tags
if (e.settings.exclude_inputs) {
tempRows = exclude_inputs(tempRows);
}
e.tableRows.push(tempRows);
});
e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
},
tableToExcel: function (table, name, sheetName) {
var e = this, fullTemplate = "", i, link, a;
e.format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
e.ctx = {
worksheet: name || "Worksheet",
table: table,
sheetName: sheetName
};
fullTemplate = e.template.head;
if ($.isArray(table)) {
Object.keys(table).forEach(function (i) {
//fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
});
}
fullTemplate += e.template.mid;
if ($.isArray(table)) {
Object.keys(table).forEach(function (i) {
fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
});
}
fullTemplate += e.template.foot;
for (i in table) {
e.ctx["table" + i] = table[i];
}
delete e.ctx.table;
var isIE = navigator.appVersion.indexOf("MSIE 10") !== -1 || (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1); // this works with IE10 and IE11 both :)
//if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // this works ONLY with IE 11!!!
if (isIE) {
if (typeof Blob !== "undefined") {
//use blobs if we can
fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
fullTemplate = [fullTemplate];
//convert to array
var blob1 = new Blob(fullTemplate, { type: "text/html" });
window.navigator.msSaveBlob(blob1, getFileName(e.settings));
} else {
//otherwise use the iframe and save
//requires a blank iframe on page called txtArea1
txtArea1.document.open("text/html", "replace");
txtArea1.document.write(e.format(fullTemplate, e.ctx));
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings));
}
} else {
var blob = new Blob([e.format(fullTemplate, e.ctx)], { type: "application/vnd.ms-excel" });
window.URL = window.URL || window.webkitURL;
link = window.URL.createObjectURL(blob);
a = document.createElement("a");
a.download = getFileName(e.settings);
a.href = link;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
return true;
}
};
function getFileName(settings) {
return (settings.filename ? settings.filename : "table2excel");
}
// Removes all img tags
function exclude_img(string) {
var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
return string.replace(/<img[^>]*>/gi, function myFunction(x) {
var res = _patt.exec(x);
if (res !== null && res.length >= 2) {
return res[2];
} else {
return "";
}
});
}
// Removes all link tags
function exclude_links(string) {
return string.replace(/<a[^>]*>|<\/a>/gi, "");
}
// Removes input params
function exclude_inputs(string) {
var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x) {
var res = _patt.exec(x);
if (res !== null && res.length >= 2) {
return res[2];
} else {
return "";
}
});
}
$.fn[pluginName] = function (options) {
var e = this;
e.each(function () {
if (!$.data(e, "plugin_" + pluginName)) {
$.data(e, "plugin_" + pluginName, new Plugin(this, options));
}
});
// chain jQuery functions
return e;
};
})(jQuery, window, document);
Related
I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
if (url !== '' && url != '-1') {
if (active) {
hideEstoques(active);
}
var target = document.getElementById("productInfo" + productId);
target.innerHTML = generateRows(productId);
target.style.display = "block";
active = productId;
}
}
function hideEstoques(productId) {
document.getElementById("productInfo" + productId).style.display = "none";
active = null;
}
function generateRows(productId) {
var rows = '';
rows += generateRowsEstoque(productId);
rows += generateRowsReserva(productId);
return rows;
}
function generateRowsEstoque(productId) {
var textContent = searchE(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse[0].nothing : null;
if (!data)
return '<span>Nothing</span><table><tr><td>Nothing</td></tr></table>';
var rows = '<span>Nothing</span> <table><thead> <tr> <th>Nothing</th></tr> </thead> <tbody>';
for(var n=0; n < data.length; n++) {
rows += '<tr>' +
'<td>' + data[n].nothing + '</td>' +
'</tr>';
}
rows += '</tbody> </table>';
return rows;
}
function searchE(productId) {
var view_data = "[]";
jQuery.ajax({
url: url + "product/" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function generateRowsReserva(productId) {
var textContent = searchEReserva(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse : null;
if (!data)
return '<table class="info"><tr><td class="none">Nothing</td></tr></table>';
var foo = data.filter(function(p) { return p.idType === 'foo' });
var bar = data.filter(function(p) { return p.idType === 'bar' });
var fooQtd = foo.length ? foo[0].nothing : 0;
var barQtd = bar.length ? bar[0].nothing : 0;
var rows = '<br/><table class="info"><thead> <tr class="labels"> <th>Nothing</th> </tr> </thead> <tbody>';
rows += '<tr>' +
'<td>' + fooQtd + '</td>' +
'<td>' + barQtd + '</td>' +
'</tr>';
rows += '</tbody> </table>';
return rows;
}
function searchEReserva(productId) {
var view_data = "[]";
$j.ajax({
url: "url" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function startLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "";
}
}
function stopLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "none";
}
}
HTML:
<td
onclick="showEstoque(1);">
<div id="estoque_1" class="estoqueCor st-color_"/>">1</div>
<img id="imgEstoqueProduto"
style="vertical-align: middle; display: none;"
src="<c:url value="/images/ajaxLoader.gif"/>">
<div class="container-product-info">
<div onmouseout="hideEstoques(1);"
class="productInfo"
id="productInfo1"></div>
</div>
</td>
I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API
When I am using that with Asp-bound field it's working perfectly
look column one is Ellipsed
But when using on template field link button it's returning blank
see it's blank I don't know what should I do to apply the same on the link button columns fields any suggestion?
my script for Eclipsed
function pageLoad() {
var table = $('#gvTest ').DataTable({
select: true,
pageLength: 15,
lengthChange: false,
scrollY: "400px",
scrollX: true,
scrollCollapse: false,
order: [15],
fixedColumns: true,
columnDefs: [
{ targets: 0, render: $.fn.dataTable.render.ellipsis(7, true) },
{ targets: 1, render: $.fn.dataTable.render.ellipsis(10, true) },
],
fixedColumns: {
leftColumns: 1,
}
});
$('#BtnReport').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var suid = ids;
var usr = document.getElementById("lblUser").innerText;
var url2 = "/report/FinalizedReport.aspx?UID=" + suid + "&" + "user=" + usr;
window.open(url2, '_blank');
return false;
});
$('#btnAssign').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var suid = ids;
var usr = document.getElementById("lblUser").innerText;
var url2 = "/PatientAssignment/PatientAssignPage.aspx?UID=" + suid + "&" + "user=" + usr;
window.location.assign(url2);
return false;
});
$('#btnAttach').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var arun = ids;
if (arun) {
var width = 700;
var height = 350;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
params += ', directories=no';
params += ', location=no';
params += ', menubar=no';
params += ', resizable=no';
params += ', scrollbars=no';
params += ', status=no';
params += ', toolbar=no';
var strWindowFeatures = params;
var URL = "/Attachment/PatientAttachmentPage.aspx?";
var usr = document.getElementById("lblUser").innerText;
URL = URL + "pattUID=" + arun + "&" + "user=" + usr; +"&" + "url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
}
else {
var a = "Select Patient";
alert(a);
}
return false;
});
$('#btnHistory').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var arun = ids;
if (arun) {
var width = 700;
var height = 350;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
params += ', directories=no';
params += ', location=no';
params += ', menubar=no';
params += ', resizable=no';
params += ', scrollbars=no';
params += ', status=no';
params += ', toolbar=no';
var strWindowFeatures = params;
var URL = "/History/WriteHistory.aspx?";
var usr = document.getElementById("lblUser").innerText;
URL = URL + "pattUID=" + arun + "&" + "user=" + usr; +"&" + "url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
}
else {
var a = "Select Patient";
alert(a);
}
return false;
});
$('#btnEmergency').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var suid = ids;
if (suid) {
document.getElementById("pattUID").value = suid;
$('#hdnEM').trigger('click');
return false;
}
else {
var a = "Select Patient";
alert(a);
}
return false;
});
$('#btnRemoveEm').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[14];
});
var suid = ids;
if (suid) {
document.getElementById("pattUID").value = suid;
$('#hdnREM').trigger('click');
return false;
}
else {
var a = "Select Patient";
alert(a);
}
return false;
});
$.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
}
below is my grid view
<asp:GridView ID="gvTest" Width="100%" runat="server" CssClass="display" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" >
</asp:BoundField>
<asp:TemplateField HeaderText="Patient Name" SortExpression="PatientName">
<ItemTemplate >
<asp:LinkButton ID="lnkVwr" Text='<%#Eval("PatientName") %>' OnClientClick = "return imgViewer(this)" runat="server" ></asp:LinkButton
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
How can I use this on link button field?
Is there any way to do that?
A link in the GridView should look like this:
<a onclick="return imgViewer(this);" id="lnkVwr" href="javascript:__doPostBack('ctl00$gvTest$ctl11$lnkVwr','')">VDWWD</a>
But after Ellipsis, it looks like this:
<span class="ellipsis" title="<a onclick="return imgViewer(this);" id="lnkVwr" href="javascript:__doPostBack('ctl00$gvTest$ctl11$lnkVwr','')" style="color:#000000!important">VDWWD</a>"><a…< span=""></a…<></span>
As you can see, it made a complete mess of the HTML and it's no wonder the browser does not know what to do with it.
On top of that, it seems that this function doesn't do anything or does not gets called:
.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml )
Take a look on this page how it is done.
I made the following snippet. It checks if an href is present in the string and if there is, it skips the trimming of the string.
<script type="text/javascript">
function pageLoad() {
var table = $('#gvTest').DataTable({
fixedColumns: true,
columnDefs: [
{ targets: 0, render: $.fn.dataTable.render.ellipsis() },
{ targets: 1, render: $.fn.dataTable.render.ellipsis() },
],
});
}
$.fn.dataTable.render.ellipsis = function () {
return function (data, type, row) {
if (type !== 'display') {
return data;
}
if (data.length > 10 && !data.includes("href")) {
return data.substr(0, 10) + '…';
} else {
return data;
}
}
};
</script>
I currently have two external scripts for my site that both require the use of onLoad. They are:
One that automatically generates a table of contents:
window.onload = function () {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
};
And another that is used to find certain words in a paragraph and replace them with given JavaScript.
var doc, bod, E, makeLink;
var pre = onload;
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id) {
return doc.getElementById(id);
}
T = function(tag) {
return doc.getElementsByTagName(tag);
}
makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
However, as they're both using onLoad, they don't work together. Is there a way to get them both to function on the same page?
functionA() {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
}
functionB() {
var doc, bod;
//var pre = onload;
//onload = function(){
//if(pre)pre();
doc = document; bod = doc.body;
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
}
window.E = function(id) {
return doc.getElementById(id);
}
window.T = function(tag) {
return doc.getElementsByTagName(tag);
}
window.makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
Then you call onload from body tag(If you want one to execute before the other, change the order):
<body onload="functionA(); functionB();">
Use addEventListener instead of setting the property of the window object. Here's a MDN page.
You can do something like that:
window.addEventListener('load', function() {
console.log('Loaded 1');
});
window.addEventListener('load', function() {
console.log('Loaded 2');
});
Both of them should fire off.
I am writing an extension for a text-editor (Brackets) that can generate HTML and append libraries automatically in the HTML.
I have an Object called 'choice'.
This modal requests the users input:
choice grabs the user's input by defining methods on choice
partial JS here:
var choice = new Object();
choice.language = function () {
//Buid HTML top 'head'
var htmlTop = "<!DOCTYPE html>" + "<html>" + "<head lang='";
//Grab Selected Language Type
var languageChoice = document.getElementById("languages").value;
//Determine what Selected Language type is and complete HTML 'head'
if (languageChoice === "english") {
languageChoice = "en";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "german") {
languageChoice = "de";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "spanish") {
languageChoice = "es";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "french") {
languageChoice = "fr";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "italian") {
languageChoice = "it";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "chinese") {
languageChoice = "zh-cn";
return htmlTop + languageChoice + "'>";
}
}; //end choice.language
choice.charset = function () {
//Build meta and the rest of the 'head tag'
var htmlCharset_Beginning = "<meta charset='";
var htmlCharset_End = "'>" + "<title> -Insert Title- </title>" + "<!-- Insert CSS links below -->" + "</head>" + "<body>";
var charsetChoice = document.getElementById("charset").value;
if (charsetChoice === "utf8") {
charsetChoice = "UTF-8";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
} else {
charsetChoice = "UTF-16";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
}
}; // end choice.charset
choice.doctype = function () {
var doctypeChoice = document.getElementById("doctype").value;
return doctypeChoice;
}; // end doctype
choice.libraries = function () {
var checkedBoxes = getCheckedBoxes("lib_checkboxes");
checkedBoxes.forEach(function(item){
var scripts =+ $(item).data('script');
});//End forEach
var bottomHTML = scripts + "</body>" + "</html>";
return bottomHTML;
}; //End choice.libraries
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
//Get checkedBoxes function
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
} // End action();
//JEFF STOP CODING HERE
// Register the commands and insert in the File menu
CommandManager.register(Strings.MENU_COMMAND, 'templates', action);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
menu.addMenuDivider();
menu.addMenuItem('templates');
}); //end define;
QUESTION:
Can I save multiple methods (each method returns a string) as a variable?
Example here:
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
My code is loading with no errors, but its not executing at all so I am trying to debug and figure out what is going wrong...
Before you realize the function 'chosenTemplate', you should check whether the document stream of the page has already downloaded. If it not, you may not be able to get the value of the widget (empty).
I know it sounds stupid, but i have no idea how to call my function from "onclick" function?
I made own class and what i wanna do is to call my function inside a class.
I have tried various stuff inside that onclick function:
function(){this.getWidth()}
this.getWidth()
Test.getWidth()
function Datagrid(_parent, _data)
{
this.table = [];
this.parent = $("#"+_parent)[0] ? $("#"+_parent) : ($("."+_parent)[0] ? $("."+_parent) : ($(+_parent)[0] ? $(_parent) : null));
this.data = _data;
this.Datagrid = function(parent,data)
{
this.setParent(parent);
if(data != null)
this.setData(data);
return this;
}
this.setParent = function(parent)
{
return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}
this.getParent = function()
{return this.parent;}
this.setData = function(data)
{this.data = data;}
this.buildTable = function()
{
var dtTbl = [];
dtTbl.push('<table class="TimeSheetmainTable" cellpadding="10" cellspacing="0" border="0">');
var style;
//Header//////////////////////
dtTbl.push('<tr class="header">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
dtTbl.push('</tr>');
//Content//////////////////////
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
dtTbl.push('<tr ' + style + ' >');
for(var c in this.data.row[r].cell)
{
dtTbl.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
}
dtTbl.push('</tr>');
}
//Footer//////////////////////
dtTbl.push('<tr class="footer">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td> </td>');
}
dtTbl.push('</tr></table>');
this.parent.html(dtTbl.join(''));
}
this.buildTableDiv = function()
{
var tableString = [];
//Header//////////////////////
tableString.push('<div class="container"><div class="header"><table><tr id="header">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
tableString.push('</tr></table></div>');
//Content//////////////////////
tableString.push('<div class="content"><table>');
var TD1 = new Object();
var TD2 = new Object();
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
for(var c in this.data.row[r].cell)
{
if(c == 0)
{ if(TD1.value != this.data.row[r].cell[c].value){
TD1.value = this.data.row[r].cell[c].value;
TD1.show = true;
}
else
TD1.show = false;
}
if(c == 1)
{ if(TD2.value != this.data.row[r].cell[c].value){
TD2.value = this.data.row[r].cell[c].value;
TD2.show = true;
}
else
TD2.show = false;
}
if(TD1.show && c == 0){//First line
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '"><input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
{
tableString.push('<td> </td>');
}
tableString.push('</tr>');
}
else if(TD2.show && c == 1)//Second line
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
{
tableString.push('<td> </td>');
}
tableString.push('</tr><tr id="content" ' + style + ' ><td> </td><td> </td>');
}
else if(!TD2.show && c == 1)//third line (distincts second cells name)
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '"> </td>');
}
else if(c > 1)//Rest filling (not ordered stuff)
{
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value.replace(""," ") + '</td>');
}
}
tableString.push('</tr>');
// $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
}
tableString.push('</table></div>');
//Footer//////////////////////
tableString.push('<div class="footer"><table><tr id="footer">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td> </td>');
}
tableString.push('</tr></table></div></div>');
this.parent.html(tableString.join(''));
// Setting width to all cells
for (var i in this.data.row[0].cell)
{
cell = parseInt(i)+1;
var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var width = h > c ? h : (c > f ? c : f);
this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
}
// this.activateScroller(0);
}
this.getScrollerWidth = function()
{
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
this.activateScroller = function(value)
{
var d = [];
d.push('<div style="height: ' + this.parent.children(":first").children(".content").height() + '; width:20px; background:#FFF"><div style="background:#333; height:200"> </div></div>');
this.parent.children(":first").children(".content").scrollTop(value);
}
expandParent = function()
{
alert(this.parent);
}
};
i am kinda makig datagrid based on javascript. i am not allowed to use jQuery UI.
My datagrid is made from tables. now i try to add a button inside a td element like User Name
The problem is that i cant access my function inside my class without making instance. is it even possible to do that without making an instance?
Once your html is generated using your generateHTML function, the handler for onclick on div looses context of what "this" is. To be more specific, this in onclick handler for div refers to that div node in DOM.
To access getWidth method you have to make it available to global context or (better solution) do something like this:
// new version of your generateHTML function
this.generateHTML() {
var str = [];
str.push('<div><input type="button" value="button"/></div>');
var that = this;
$("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}
EDIT:
To further explain how code above works, here's simplified example with comments.
Test = function() {
this.generate = function() {
var newnode = $('<button>click me</button>');
$("body").append(newnode);
// "cache" this in a variable - that variable will be usable in event handler
var that = this;
// write event handler function here - it will have access to your methods by using "that" variable
newnode.click(function(e) {
// here this refers to button not Test class
// so we have to "reach" to outer context to gain access to all methods from Test
that.doSomething('learn');
})
}
this.doSomething = function(x) {
alert('do it: '+x);
}
}
// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();