How to arrange array values on a table for email? - javascript

Sorry for the vague title. I'm really new to programming and I have this code here:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Confirm Order')
.addItem('Send Email', 'email')
.addToUi();
}
function email() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var currentRow = sheet.getActiveRange().getRow();
var product = sheet.getRange(2,5,1,11).getValues(); //header names
var order1 = sheet.getRange(currentRow, 5, 1,11).getValues();
var order2 = sheet.getRange(currentRow, 17, 1,11).getValues();
var order3 = sheet.getRange(currentRow, 29, 1,11).getValues();
var email = sheet.getRange(currentRow,2).getValues();
var tab = ""
var z ="";
for(var i in product){
if(product[i]!="") z += "<tr><td style='padding:5px'>" + product[i] + "</td><td style='padding:5px'>" + order1[i] + "</td><td style='padding:5px'>" + order2[i] + "</td><td style='padding:5px'>" + order3[i] + "</td></tr>";
}
tab = "<table><tr><th>Product Name</th><th>Order 1</th> <th>Order 2</th> <th>Order 3</th></tr>" + z + "</table>";
// MailApp.sendEmail(Session.getActiveUser().getEmail(),"Your report", report, {htmlBody: report});
MailApp.sendEmail(email,"Order Confirmation", tab, {htmlBody: tab});
}
The following code sends out an email of a selected data in a spreadsheet, however the results in email are not one below another. For example, I want it to look like this:
Product Name order 1 order 2 order 3
prod A 2 2 1
prod B 3 1 4
Prod C 12 7 9
But it ends up looking like this:
Product Name order 1 order 2 order 3
prod A,prod B,prod C 2,3,12 2,1,7 1,4,9
Please tell me what I'm doing wrong. I really wanted to learn.

getValues returns a 2d array. This is why product[0] displays as "prod A,prod B,prod C". That's the arrays toString function at work. So you need to print product[0][0], product[0][1], product[0][2].
for(var i in product) {
for (var j in product[i]) {
z += "<tr><td style='padding:5px'>" + product[i][j] + "</td><td style='padding:5px'>" + order1[i][j] + "</td><td style='padding:5px'>" + order2[i][j] + "</td><td style='padding:5px'>" + order3[i][j] + "</td></tr>";
}
}
This assumes product, order1, order2, and order3 all have the same size.

Related

How to update multiple table rows into mysql table when click save button using Jquery and PHP?

I have a myql table name - invoice_details
invoice_number received_amount receiptID
1000 0.00
1001 0.00
1005 0.00
I have a html table
When clicking the save button, update invoice_details table with received amount and receiptID where invoice number in the html table row (1001,1005) Multiple rows will be there in html table.
appending this html table code:
$('#invoicelist_receipt').find('tbody').remove();
$.each($("input[name='myTextEditBox[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
// values += $(data).find('td:eq(0)').text() + "," + $(data).find('td:eq(1)').text() + "," + $(data).find('td:eq(2)').text() + ",";
var t1 = $(data).find('td:eq(0)').text();//invoice date
var t2 = $(data).find('td:eq(1)').text();//invoice no
var t3 = $(data).find('td:eq(2)').text();//invoice amt
trtoggle += "<tr><td class=''>" + t1 + "</td><td name='invoice_no_receipt[]' class='invoice_no_receipt'>" + t2 + "</td><td class=''>" + t3 + "</td><td class=''><input class='form-control invoice_amt_receipt' type='number' data-type='invoice_amt_receipt' id='invoice_amt_receipt_1' name='invoice_amt_receipt[]' for='1'/></td></tr>";
//values.push({ 'invoicedate':$(data).find('td:eq(0)').text(), 'invoiceno':$(data).find('td:eq(1)').text() , 'invoiceamount':$(data).find('td:eq(2)').text()});
});
$("#invoicelist_receipt").last().append(trtoggle);
when button clicks:(creating a new receipt)
var invoice_no_receipt = []; //where invoice no = 1000,1001,1005 etc..
var invoice_amt_receipt = [];//this received amount i have to update into database - invoice details table
$('.invoice_no_receipt').each(function() {
invoice_no_receipt.push($(this).val());
});
$('.invoice_amt_receipt').each(function() {
invoice_amt_receipt.push($(this).val());
});
$.ajax({
url: base_url + "index.php/welcome/savereciptfinal/",
type: "POST",
data: {
"getinvnumber": invoice_no_receipt,
"getinv_recived_amount": invoice_amt_receipt
},
success: function(data) {
}
});
PHP Codeigniter code
public function savereciptfinal()
$value2 = "0001"; //autogenerate number
$value = $value2;
$data = array(
'rece_No' => $value
);
$insert_id = 0;
if ($this->db->insert("receipt_details", $data)) {
$insert_id = $this->db->insert_id();
}
$data2 = array(
'rece_Amt' => $this->input->post('getrece_amt'),
'receipt_ID' => $value2; //the above auto generated number i need to update invoice_details for column receiptID
);
$this->db->where('invoice_No ', $inv_id);
$this->db->update('invoice_details', $data2);
}
You can get ideas from this code and sync it with your own code
First clear this script:
$('#invoicelist_receipt').find('tbody').remove();
$.each($("input[name='myTextEditBox[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
var t1 = $(data).find('td:eq(0)').text();//invoice date
var t2 = $(data).find('td:eq(1)').text();//invoice no
var t3 = $(data).find('td:eq(2)').text();//invoice amt
trtoggle += "<tr><td class=''>" + t1 + "</td><td name='invoice_no_receipt[]' class='invoice_no_receipt'>" + t2 + "</td><td class=''>" + t3 + "</td><td class=''><input class='form-control invoice_amt_receipt' type='number' data-type='invoice_amt_receipt' id='invoice_amt_receipt_1' name='invoice_amt_receipt[]' for='1'/></td></tr>";
});
$("#invoicelist_receipt").last().append(trtoggle);
Set your save button id instead of 'your_save_button_id'
You can see how send your invoice details in js
$(document).on('your_save_button_id', 'click', function(){
var invoice_no_receipt = [];
$('.invoice_no_receipt').each(function() {
// Json format to add product invoice detail
var invoice_detail = new Object();
// Get invoice number
invoice_detail.no = $(this).text();
// Get parent tr
var parent_tr = $(this).closest('tr');
// Get amount
invoice_detail.amt = $(parent_tr).find('invoice_amt_receipt').val();
// Add invoice detail to invoice_no_receipt
invoice_no_receipt.push(invoice_detail);
});
$.ajax({
url: base_url + "index.php/welcome/savereciptfinal/",
type: "POST",
data: {
"invoice_no_receipt": invoice_no_receipt
},
success: function(data) {
}
});
})
You can see how can get your invoice detail in PHP
IN Your PHP code in ajax function
// Get invoice_no_receipt
$invoice_no_receipt = $_POST('invoice_no_receipt');
foreach( $invoice_no_receipt as $item )
{
// Get invoice number
$invoice_no = intval($item['no']);
// Get invoice amount
$invoice_amt = floatval($item['amt']);
// Update your invoice in db one by one and by use from these variable
// Your update function
}

Email a table from google sheets using app script - on click of a button

I am new to coding. This is my first query. Pardon me for mistakes.
I want to develop a simple code to take orders from customers. In the attached sheet - customers will select their products and a summary email should go to the customer's email id and the admin email id.
The email is getting sent with the correct subject line but the email body is incorrect.
The email body is - [object Object] - instead of the table with product details.
Below is the code. Please help. Thanks in advance.
https://docs.google.com/spreadsheets/d/1J4OHwN3MEJwqMhOMDWg2Mt6dgqjcVlGOc2bHOS5lmRY/edit#gid=1167211647
"Sheet - Order tab"
function orderemail() {
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);
var emailAddress = "chhedapriyank#gmail.com";
var emailAddress2location = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order tab").getRange("C25");
var emailAddress2 = emailAddress2location.getValues();
// Send Alert Email.
var order = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order tab").getRange("A2:K32");
var message = order.getValues();
var subject = 'New Order Alert';
var subject2 = 'Order Summary';
MailApp.sendEmail(emailAddress, subject, {htmlBody: htmltable})
MailApp.sendEmail(emailAddress2, subject2, {htmlBody: htmltable})
var reset = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order tab").getRange("b3:j22");
reset.clearContent();
var reset2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order tab").getRange("c25");
reset2.clearContent();
}
if I understand well the doc https://developers.google.com/apps-script/reference/mail/mail-app
you don't have to pass an object as the body parameter of MailApp.sendEmail, but directly your text/html
so replace {htmlBody: htmltable} by htmltable in these lines :
...
MailApp.sendEmail(emailAddress, subject, htmltable)
MailApp.sendEmail(emailAddress2, subject2, htmltable)
...
edit
you need to provide a text body before providing the options object,
sendEmail(recipient, subject, body, options)
you were right about the syntax but you need a text before.
you can try this to test it :
...
MailApp.sendEmail(emailAddress, subject, htmltable, {htmlBody: htmltable})
MailApp.sendEmail(emailAddress2, subject2, htmltable,{htmlBody: htmltable})
...
but I recommend you create a text version of your data and pass it as the text body if it works
to answer your further questions (from comment)
1 if you don't want blank to be "None" you should remove this part
var htmltable = '<table ' + TABLEFORMAT +' ">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 0 ;col<data[row].length; col++){
//remove this part ------------
//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>';
}
2 - try this
...
// Send Alert Email.
var order = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order tab").getRange("A2:K32");
var message = order.getValues();
//---------------------- this :
var customerId = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Order tab").getRange("c24")
.getValues()[0];
var subject = 'New Order Alert - ' + customerId;
var subject2 = 'Order Summary - ' + customerId;
...
```

How do I convert a 'undefined' or 'zero' value to string?

When I retrieve cell value from google sheet with google app script then it returns 'undefined' when the value in that cell is 'zero'. I need it to be remain zero when I send the values to a email.Image Result of the cell value where value is zero in google sheet
function sendEmails() {
var app = SpreadsheetApp;
var targetSheet = app.getActiveSpreadsheet().getSheetByName("Template");
var i,j; var k=4;
for(i=2; i<=2; i++){
var infoData = [];
for(j=2; j<=5; j++){
var cellValues = targetSheet.getRange(i, j).getValue();
infoData.push(cellValues);
}
var emailSheet = app.getActiveSpreadsheet().getSheetByName("Emails");
var currentEmail = app.getActiveSheet().activate().getRange(i, 1).getValue();
var subject = app.getActiveSheet().activate().getRange(i, 2).getValue();
var block = app.getActiveSheet().activate().getRange(i, 3).getValue();
//var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
//Logger.log("Remaining email quota: " + emailQuotaRemaining);
var body = "<h3>Dear Sir/Ma'am,</h3>" +
"<h3>Daily MGNREGA progress Report on different parameters.</h3>" +
"<table border = '1'>" +
"<tr><td>BLOCK: </td><td>" + block + "</td><tr>" +
"</table>" +
"<table border = '1'>" +
"<tr font-style = 'bold'><td>#S.NO</td> <td align = 'center'> PARAMETERS </td><td align = 'center'> VALUES </td></tr>" +
"<tr><td align = 'center'>1.</td> <td align = 'left'> Percentage of NRM Expenditure for the financial year 2019-20 (So far) </td><td align = 'right'>" + infoData[0] + "</td></tr>" +
"<tr><td align = 'center'>2.</td> <td align = 'left'> Percentage of Timely MGNREGA wage payment (T+8 days) FY 2019-20 </td><td align = 'right'>" + infoData[1] + "</td></tr>" +
"<tr><td align = 'center'>3.</td> <td align = 'left'> Work completion rate FY 2017-18 and Earlier in percentage</td><td align = 'right'>" + infoData[2] + "</td></tr>" +
"<tr><td align = 'center'>4.</td> <td align = 'left'> No. of Rejected transactions pending Reconcilation of FY 2018-19 </td><td align = 'right'>" + infoData[3] + "</td></tr>" +
"<tr><td align = 'center'>5.</td> <td align = 'left'> Pending Geotagging Stage- 3 of Phase-II (Completed Works) </td><td align = 'right'>" + infoData[4] + "</td></tr>" +
"<tr><td align = 'center'>6.</td> <td align = 'left'> FTOs Pending for First signatory FY 2019-20 </td><td align = 'right'>" + infoData[5] + "</td></tr>" +
"<tr><td align = 'center'>7.</td> <td align = 'left'> FTOs Pending for Second signatory FY 2019-20 </td><td align = 'right'>" + infoData[6] + "</td></tr>" +
"<tr><td align = 'center'>8.</td> <td align = 'left'> No. of Rejected transactions pending Reconcilation FY 2019-20 </td><td align = 'right'>" + infoData[7] + "</td></tr>" +
"</td></tr>" +
"</table>" +
"<h4>NOTE: This Alert message is valid for Today only. Thanks</h4>" +
"<h3>Regards,</h3>" +
"<h3>DRDA Barpeta</h3>";
var options = {
htmlBody : body
}
MailApp.sendEmail(currentEmail, subject, "", options);
}
}
You can set a default value to cellValue by adding a || 0 so that the cellValue gets set as 0 if targetSheet.getRange(i, j).getValue() returns undefined
Try this
var cellValues = targetSheet.getRange(i, j).getValue() || 0;
It'd be really helpful if we could tell what the raw data of infoData was (I'm not all too familiar with Google App Scripts), but I'll do my best. Now, this isn't code golf, but we can detect and replace all undefined values with 0 with a for loop.
var i;
for (i = 0; i < infoData.length; i++) {
if (infoData[i] == undefined) {
infoData[i] = 0;
}
}
Hope this helps!

Array.sort not working correctly

I need the sort function to sort the dates from the earliest date to the latest date. What can I do to fix this in my tasks table?
var tasks = new Array();
var index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
//add array and populate from tempdate and temptask
//generate html table from 2d javascript array
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a,b){return new Date(b.Date).getTime() - new Date(a.Date).getTime()});
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
I have tried many different syntax variations and can not get the sort function to sort in descending order
Since the date is represented as
the number of milliseconds since 1 January, 1970 UTC (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
the sorting order you are looking for is ascending not descending.
Also, as #birdspider already commented, there is no use of creating new Date objects and invoking the getTime() method. They are comparable as they are.
To summarize the above points, try using the following sorting function:
function sortDatesAsc(tempdateA, tempdateB) {
return tempdateA - tempdateB < 0 ? -1 : (tempdateA > tempdateB ? 1 : 0);
}
tasks.sort(sortDatesAsc);
You're subtracting a.Date from b.Date, exactly the reverse of what you want.
Flip those around (and remove the unnecessary new Date() wrappers, although they're not actually breaking anything) and you'll get the correct sort:
var tasks = [],
index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a, b) {
return a.Date.getTime() - b.Date.getTime()
});
var tablecode = "<table class='tasktable'>" +
"<tr>" +
"<th>Date</th>" +
"<th>Task</th>" +
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode += "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode += "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
document.getElementById('add').addEventListener('click', addTask);
<p>Task:
<input type="text" id="taskinfo" /></p>
<p>Date:
<input type="date" id="taskdate" /></p>
<button id="add">add</button>
<div id="bottomright"></div>

JavaScript works in Chrome but not ie9 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am facing an issue with JavaScript.I see that it works fine in chrome but not in IE9.This would not display what chrome is displaying on the web page as expected.
I am new to JavaScripting can I get help in fixing this issue.
<script type="text/javascript">
var tds = document.getElementById('course_table')
.getElementsByTagName('td');
var sum = 0;
for (var i = 0; i < tds.length; i++) {
if (tds[i].className == 'count-me') {
sum += isNaN(tds[i].innerHTML) ? 0
: parseInt(tds[i].innerHTML);
}
}
var lastrecord = tds[tds.length - 2].innerHTML;
var table = document.getElementById('course_table')
.getElementsByTagName('tr');
var max = table.length - 2;
document.getElementById('course_table').innerHTML += '<tr bgcolor=#FFCCFF><td></td><td>Total Courses</td><td>' + max + '</td><td>Total Credits Remaining</td><td>'+ sum + '</td><td> Expected Graduation Date</td><td></td><td>' + lastrecord + '</td><td></td></tr> ';
</script>
Thanks
Niveditha
The problem is most likely in the last line:
document.getElementById('course_table').innerHTML += '<tr bgcolor=#FFCCFF><td></td><td>fsffd</td><td>' + max + '</td><td>abcdRemaining</td><td>'+ sum + '</td><td> abc</td><td></td><td>' + lastrecord + '</td><td></td></tr> ';
IE doesn't handle trs being added by strings; besides it is non-standard. Replace that line with this, it programmatically builds up the row and is faster. I added the corresponding <td> as comments.
var table = document.getElementById('course_table');
var row = table.insertRow(-1);
row.style.backgroundColor = '#FFCCFF'; // `bgcolor` attribute is deprecated
row.insertCell(-1); // <td></td>
row.insertCell(-1).textContent = "fsffd"; // <td>fsffd</td>
row.insertCell(-1).textContent = max; // <td>' + max + '</td>
row.insertCell(-1).textContent = "abcdRemaining"; // <td>abcdRemaining</td>
row.insertCell(-1).textContent = sum; // <td>' + sum + '</td>
row.insertCell(-1).textContent = "abc"; // <td> abc</td>
row.insertCell(-1); // <td></td>
row.insertCell(-1).textContent = lastRecord; // <td>' + lastRecord + '</td>
row.insertCell(-1); // <td></td>
The important methods here are insertRow and insertCell, they are guaranteed to work. textContent is faster and safer than innerHTML. Please use CSS instead of the deprecated bgcolor attribute
Internet Explorer doesn't like adding <tr> elements to the <table> in that manner. What you can do is append a new <tbody> element to the table:
// ... the first part of your function ...
var lastrecord = tds[tds.length - 2].innerHTML;
var table = document.getElementById('course_table');
var newbody = document.createElement('tbody');
newbody.innerHTML = '<tr bgcolor=#FFCCFF><td></td><td>Total Courses</td><td>' + max + '</td><td>Total Credits Remaining</td><td>'+ sum + '</td><td> Expected Graduation Date</td><td></td><td>' + lastrecord + '</td><td></td></tr> ';
table.appendChild(newbody);

Categories

Resources