Date format in HTML table - javascript

I am having trouble changing the date format in my HTML table. I want it to display as "9/1/22" but I am getting "Thu Sep 01 2022 16:55:58 GMT-0400 (Eastern Daylight Time)"
Here is my code:
function sampleFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
range = sh.getRange("E1").getValues();
var data = sh.getRange(range).getValues();
//var htmltable =[];
var TABLEFORMAT =
'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;';
var htmltable = "<table " + TABLEFORMAT + ' ">';
for (row = 0; row < data.length; row++) {
htmltable += "<tr>";
for (col = 0; col < data[row].length; col++) {
if (data[row][col] === "" || 0) {
htmltable += "<td>" + "None" + "</td>";
} else if (row === 0) {
htmltable += "<th>" + data[row][col] + "</th>";
} else {
htmltable += "<td>" + data[row][col] + "</td>";
}
}
htmltable += "</tr>";
}
htmltable += "</table>";
Logger.log(data);
Logger.log(htmltable);
MailApp.sendEmail(Session.getActiveUser().getEmail(), "Daily report", "", {
htmlBody: htmltable,
});
}
Any help would be greatly appreciated

You can use the Date object to do that:
var today = new Date();
console.log(today.toLocaleDateString("en-US")); // 9/4/2022
I don't know in which column your date data (you need to post the data in data object) but lets say the date is in the first column then you can do this:
var data = [];
var TABLEFORMAT =
'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;';
var htmltable = "<table " + TABLEFORMAT + ' ">';
for (var row = 0; row<data.length; row++){
var formattedDate = new Date(data[row][0]).toLocaleDateString("en-US")
htmltable += '<tr>';
for (var col = 0 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
else {
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
}
else if (col === 0) { htmltable += '<td>' + formattedDate + '</td>'}
else {
htmltable += '<td>' + data[row][col] + '</td>';
}
}
}
htmltable += '</tr>';
}
Note: I created local var data in example to make it compile. You should just use your own variables.

Related

Modify function to make names also links

I have a function that creates a table that consists of several elements all of which are taken from a saved file. The table has other information inside(url) Inside the table surname name and middle name(if exists) is put under one header "Full name". How can I modify this function so that it not only displays the name but makes it so that the name is also a url link?
var members = data.results[0].members;
createTable(members)
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td>" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</td>";
table += "<td>" + members[r].party + "</td>" + "<td>" + members[r].state + "</td>" + "<td>" + members[r].seniority + "</td>";
if (members[r].votes_with_party_pct === undefined) {
table += "<td>" + "-" + "</td>"
} else {
table += "<td>" + members[r].votes_with_party_pct + "%" + "</td>"
}
}
table += "<tr>";
}
document.getElementById("house-data").innerHTML = JSON.stringify(table);
}
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td><a href=\"YOUR_LINK_HERE\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";
...
Replace YOUR_LINK_HERE with the URL you want.
If you want to use a variable, use:
table +=
"<td><a href=\""+url+"\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";

How do I mail cell range with proper format in google sheet?

Hi this is my sheet: https://docs.google.com/spreadsheets/d/1xkTt_1kLyROkUFComi8-NiKyDMan6617C1dA5UqWTSI/edit?usp=sharing
I want to share range A2:F8 in email using google script.
As far as I can say this script works fine:
function sendMail(){
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sh.getRange("A2:O38").getValues();
//var htmltable =[];
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT +' ">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 0 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
else
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
}
else {htmltable += '<td>' + data[row][col] + '</td>';}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
MailApp.sendEmail("myemail#gmail.com", 'Daily report','' ,{htmlBody: htmltable})
}
The problem is when i get mail the merged cells are not in merged state.
This result in 3 columns instead of 1.
Can someone please tweak the code so that I get exactly like i formatted sheets.
I modified the code a little because I didn't want to send any emails. And if you'll move the table up to the top left corner and use sh.getDataRange() then you'll get the entire table with no problems.
This is my modified version.
function sendSomething(){
var sh = SpreadsheetApp.getActiveSheet();
var dataA = sh.getDataRange().getValues();
var None = ' ';
var htmltable ='';
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT +' ">';
for (row = 0; row<dataA.length; row++)
{
htmltable += '<tr>';
for(col = 0 ;col<dataA[row].length; col++)
{
if (dataA[row][col] === "" || 0)
{
htmltable += '<td>' + None + '</td>';
}
else
if (row === 0)
{
htmltable += '<th>' + dataA[row][col] + '</th>';
}
else
{
htmltable += '<td>' + dataA[row][col] + '</td>';
}
}
htmltable += '</tr>';
}
htmltable += '</table>';
dispStatus('HTML',htmltable,800,500);
}
And this is my display routine which I incorporated into your code. It's just my version of the logger.
function dispStatus(title,html,width,height,modal)
{
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 400;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var modal = typeof(modal) !== 'undefined' ? modal : false;
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
if(!modal)
{
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
else
{
SpreadsheetApp.getUi().showModalDialog(htmlOutput, title);
}
}
You still need to format the dates. Perhaps you can use Utilities and if you want to merge cells together in the header you'll need to figure out which ones to give a colspan="3".

Loop every nth item and fill the blanks

I want to build an HTML table string for every 10 items in a Javascript array, and if there are less than 10 items in the last iteration I want to fill it with empty rows.
How do I achieve this?
var array_of_items; //array of items
//make a html table string every 10 items
var table = '<table>';
table += '<tr><td>' + item1 + '</td></tr>';
table += '<tr><td>' + item2 + '</td></tr>';
.
.
.
table += '<tr><td>' + item10 + '</td></tr>';
table += '</table>';
//make second table
table = '<table>';
table += '<tr><td>' + item11 + '</td></tr>';
table += '<tr><td>' + item12 + '</td></tr>'; //array ends here
table += '<tr><td></td></tr>';
.
.
.
table += '<tr><td></td></tr>';
table += '</table>';
$('#table_div').html(table);
var table = '';
var numTables = Math.ceil(array_of_items.length / 10); //determine how many tables
for (var i=0;i<numTables;i++){
table +='<table>';
for (var j=0;j<10;j++){
(array_of_items[i*10+j] ? table +='<tr><td>' + array_of_items[i*10+j] + '</td></tr>' : table +='<tr><td></td></tr>');
}
table +='</table>';
}
var ln = items.length;
var lnten = ln + 10 - ln%10;
var container = $('#table_div');
for (var j = 0; j < lnten; j++) {
var tbl;
if (j % 10 == 0)
tbl = $('<table/>');
var tr = $('<tr/>');
var td = $('<td/>');
if (j < ln)
td.text(items[j]);
tr.append(td);
tbl.append(tr);
if (j % 10 == 0)
container.append(tbl);
}
jsfiddle DEMO
I think you're looking for this
for (var i = 0; i < array_of_items.length; i+=10) {
var table = '<table>';
for (var j = i; j < i+10; ++j) {
if (array_of_items[j] === 'undefined') {
table += '<tr><td></td></tr>';
}
else table += '<tr><td>' + array_of_items[j] + '</td></tr>';
}
table += '</table>';
}

Javascript TypeError: JSON array object is undefined

I am getting a perfectly created JSON object from server response.
For example:
{
"users": [
{
"userId": 20410,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "viralp.shah#tcs.com",
"userRole": 3
},
{
"userId": 400881,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "viralpshah123#gmail.com",
"userRole": 0
},
{
"userId": 425622,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "viralpshah123#tcs-itontap.com",
"userRole": 0
}
]
}
I am using this in JavaScript using AJAX like below:
var jsonobj2 = null;
var respObj = getSearchedWPUsers(firstname, lastname, loginid); //return json response
var len = respObj.length;
jsonobj2 = eval('(' + respObj + ')');
var tablehtml = "<table><tr><td><b>First Name</td><td><b>Last Name</td><td><b>Login Id</td><td><b>Editing Rights</td></tr><tr></tr>";
for (i = 0; i < len; i++) {
tablehtml = tablehtml + "<tr>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].lastName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].loginId;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td><b>";
var role = jsonobj2.users[i].userRole;
if (role == 1 || role == 2 || role == 3) tablehtml = tablehtml + "<a href ='javascript:removeXML(" + jsonobj2.users[i].userId + ")'><u><font color='red'>Revoke access</font></a> ";
else tablehtml = tablehtml + "<a href ='javascript:generateXML(" + jsonobj2.users[i].userId + ")'><u><font color='blue'>Assign access</font></a> ";
tablehtml = tablehtml + "</td>";
tablehtml = tablehtml + "</tr>";
}
tablehtml = tablehtml + "</table>";
document.getElementById("TableHolder").innerHTML = tablehtml;
//--------------------------
It throws errors like below
TypeError: jsonobj2.users[i] is undefined
[Break On This Error]
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tried with JSON.parse(serverresponse); -- nothing happened
Please help
Try this instead:
jsonobj2 = eval('(' + respObj + ')');
var len = jsonobj2.users.length;
As I understand, respObj is a string that contains the JSON response, but it still needs to be parsed. So, if you do respObj.length, you're getting the length of the string, but not of the users array, properly. Also, I recommend you to parse this response using JSON.parse (whenever available by the browser) instead of using eval:
var respObj = getSearchedWPUsers(firstname, lastname, loginid);
var jsonobj2 = JSON.parse ? JSON.parse(respObj) : eval('(' + respObj + ')');
var len = respObj && respObj.users ? respObj.users.length : 0;
However, as Felix Kling and Aamir Adnan said, ajax calls are mostly asynchronous, so you might pass a callback function as argument, which will process the response as your will:
getSearchedWPUsers(firstname, lastname, loginid, function(respObj){
var jsonobj2 = JSON.parse ? JSON.parse(respObj) : eval('(' + respObj + ')');
var len = respObj && respObj.users ? respObj.users.length : 0;
var tablehtml = "<table><tr><td><b>First Name</td><td><b>Last Name</td><td><b>Login Id</td><td><b>Editing Rights</td></tr><tr></tr>";
for (i = 0; i < len; i++) {
tablehtml = tablehtml + "<tr>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].lastName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].loginId;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td><b>";
var role = jsonobj2.users[i].userRole;
if (role == 1 || role == 2 || role == 3)
tablehtml = tablehtml + "<a href ='javascript:removeXML(" + jsonobj2.users[i].userId + ")'><u><font color='red'>Revoke access</font></a> ";
else tablehtml = tablehtml + "<a href ='javascript:generateXML(" + jsonobj2.users[i].userId + ")'><u><font color='blue'>Assign access</font></a> ";
tablehtml = tablehtml + "</td>";
tablehtml = tablehtml + "</tr>";
}
tablehtml = tablehtml + "</table>";
document.getElementById("TableHolder").innerHTML = tablehtml;
});

Datepicker in Javascript

What is the best way(pattern) to Create datepicker in Javascript.
I have created one using Singleton pattern, but am not satisfied.
You can just use jQuery UI Datepicker and forget about it.
1) Singleton Pattern
The Singleton pattern is often known as an "anti pattern", in other words only use it if absolutely necessary.
Is there a really good reason for all your calendars to use the same instance? I would guess not.
2) Javascript datepickers
I would recommend looking around for date picker libraries, or use jQuery.
I am a fan of http://jonathanleighton.com/projects/date-input (jQuery)
Lightweight and simple! :-)
CIC Kalender skript.
<script language="JavaScript" src="kalender.js"></script>
<script language="JavaScript">
var Singleton = new function Singleton()
{
var instance = this;
var count = 0;
var result = "";
var callBack = "";
var id = "vnd";
var d = new Date();
var days = new Array('So','Mo','Di','Mi','Do','Fr','Sa');
var months = new Array('Januar', 'Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
var month = d.getMonth();
var date = d.getDate();
var day = d.getDay();
d.setDate(1);
var firstDay = d.getDay();
d.setDate(date);
var year = d.getFullYear();
Singleton.getInstance = function()
{
return instance;
}
this.toString = function()
{
return "[object Singleton]";
}
this.instanceMethod = function()
{
alert( "instance method called!" );
}
this.setCallBack = function(callBackFuncName) {
callBack = callBackFuncName;
}
this.getFormattedDate = function() {
return date + '.' + month + '.' + year;
}
this.getLength = function() {
switch(month){
case 1:
if ((year%4==0 &&
year%100!=0) ||
year%400==0)
return 29; // leap year
else
return 28;
case 3:
return 30;
case 5:
return 30;
case 8:
return 30;
case 10:
return 30
default:
return 31;
}
}
this.setDateVariable = function() {
day = d.getDay();
month = d.getMonth();
d.setDate(1);
firstDay = d.getDay();
d.setDate(date);
year = d.getFullYear();
}
this.writeCalendar = function() {
var calString = '<div id="calContainer" >';
calString += '<table id="cal' + id + '" cellspacing="0" width="200"' + ' style="border:1px black solid;">';
calString += '<tr><th colspan="7" class="month">' + months[month] + ' ' + year + '</th></tr>';
/*
* Row containing days of the week.
*/
calString += '<tr>';
for( var i = 0; i < days.length; i++ ) {
calString += '<th class="dayHeader">' + days[i] + '</th>';
}
calString += '</tr>';
/*
* Body of the Calendar.
*/
calString += '<tr>';
for(var j = 0; j < 42; j++ ) {
var displayNum = (j-firstDay+1);
if( j < firstDay ) {
calString += '<td class="empty"></td>';
} else if ( displayNum == date ) {
calString += '<td id="' + id +
'selected" class="date" ' +
'onClick="Singleton.getInstance().changeDate(this,\'' +
id + '\')">' + displayNum + '</td>';
} else if ( displayNum > length ) {
calString += '<td> </td>';
} else if(displayNum <= date) {
calString += '<td id="" class="days" ' +
id + '\')">' + displayNum + '</td>';
}
else {
calString += '<td id="" class="days" ' +
'onClick="Singleton.getInstance().changeDate(this,\'' +
id + '\')">' + displayNum + '</td>';
}
if(j%7==6){
calString += '</tr><tr>';
}
}
/*
* close the last number row
*/
calString += '</tr>';
/*
* the nav row
*/
calString += '<tr>';
calString += '<td class="nav" ' +
'style="text-decoration:underline;"' +
' onClick="Singleton.getInstance().changeMonth(-12,\'' + id +
'\')"><</td>';
calString += '<td class="nav" ' +
'onClick="Singleton.getInstance().changeMonth(-1,\'' + id +
'\')"><</td>';
calString += '<td class="month" ' +
'colspan="3"> </td>';
calString += '<td class="nav"' +
' onClick="Singleton.getInstance().changeMonth(1,\'' + id +
'\')">></td>';
calString += '<td class="nav" ' +
'style="text-decoration:underline;text-' +
'align:right;" onClick="Singleton.getInstance().changeMonth(12,\'' +
id + '\')">></td>';
calString += '</tr>';
calString += '</table>';
calString += '</div>';
result = calString;
return calString;
}
this.changeDate = function(td) {
var oDiv = document.getElementById(id + "selected");
oDiv.className = "days";
oDiv.id = "";
td.className = id + "selected";
td.id = id + "selected";
date = parseInt(td.innerHTML);
// Create new Date object.
selected_date = new Date();
selected_date.setDate(date);
selected_date.setMonth(month);
selected_date.setYear(year);
callBack(selected_date);
}
this.changeMonth = function(mo) {
d.setMonth(d.getMonth() + mo);
this.setDateVariable();
document.getElementById("vnd").innerHTML = this.writeCalendar();
}
Singleton.staticMethod = function()
{
count = count+1;
alert( "static method called!" + count);
}
var length = this.getLength();
return Singleton;
}
function init() {
Singleton.getInstance().setCallBack(setDates);
document.getElementById("vnd").innerHTML = Singleton.getInstance().writeCalendar();
}
function setDates(date) {
//alert(date);
}
<div id="vnd" style="font-family: Calibri, Verdana">This is a Date DIV</div>

Categories