JavaScript DOM Exercises 33
JavaScript DOM Exercises 33
Do you want to learn more about JavaScript and how elements work?
They are objects which can hold values just like any other objects in
JavaScript. The three exercises below will demonstrate creating page
elements with JavaScript, how to add values to the element objects, and
how to update page elements. There is also an exercise on how they work
with the page element objects, and the difference between function
expressions and function declarations.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class="output">What is your name?</div>
<input type="text" name="userName">
<button>Submit</button>
<script src="app.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class="output"></div>
<button class="btn1">Adder 1</button>
<button class="btn2">Adder 2</button>
<button class="btn3">Adder 3</button>
///Function Declaration
function adder1(){
if(!this.total) {
this.total = 1;
}else{
this.total++;
}
output.textContent = `Total #1 : (${this.total})`;
}
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<script src="app2.js"></script>
</body>
</html>
function adder(e){
this.total++;
output.style.backgroundColor= this.style.backgroundColor;
output.innerHTML = `${this.textContent} :(${this.total})`;
}
Create interactive elements that can store the current color value input an
array, for later use. Also creates buttons to update the body background
color to the value of the button text. Color style and events with Dynamic
Elements DOM.
<!DOCTYPE html>
Laurence Svekis https://basescripts.com/
12
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<input type="color">
<script src="app4.js"></script>
</body>
</html>
btn2.onclick = ()=>{
holder.forEach((ele)=>{
const span = document.createElement('span');
main.append(span);
btn.onclick = ()=>{
holder.push(myInput.value);
//main.textContent = holder.toString();
const btn1 = document.createElement('button');
main.append(btn1);
btn1.textContent = myInput.value;
btn1.style.backgroundColor = myInput.value;
btn1.style.color = 'white';
btn1.onclick = ()=>{
document.body.style.backgroundColor = btn1.textContent;
}
}
myInput.onchange = (e)=>{
console.log(e.target.value);
console.log(myInput.value);
document.body.style.backgroundColor = myInput.value;
Using JSON data, load the json file when the DOM content is loaded. Create
the page slides dynamically with JavaScript code. Add interaction to
navigate between slides listening for clicks on the buttons.
<head>
<title>JavaScript Course</title>
<style>
* {
box-sizing: border-box;
}
.main {
width: 90vw;
margin: auto;
background-color: black;
position: relative;
height: 300px;
.slide {
text-align:center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: blue;
opacity: 0;
}
.slide.active {
opacity: 1;
}
.btn {
position: absolute;
bottom: 2rem;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
font-size: 0.9em;
color: white;
cursor:pointer;
.next {
right: 3rem;
}
.prev {
left: 3rem;
}
</style>
</head>
<body>
<div class="main">
<div>
<div class="slider">
</div>
<div class="prev btn">< Prev</div>
<div class="next btn">Next ></div>
</div>
</div>
<script src="app5.js"></script>
</body>
</html>
function mover(dir){
const cur = document.querySelector('.active');
cur.classList.remove('active');
const nex = cur.nextElementSibling ||
slider.firstElementChild;
const pre = cur.previousElementSibling ||
slider.lastElementChild;
const newActive = (dir) ? nex : pre;
newActive.classList.add('active');
}
function init(){
//console.log('ready');
fetch('app5.json')
.then(response => response.json())
function adder(data){
//slider
data.forEach((item,index)=>{
const slide = document.createElement('div');
slide.classList.add('slide');
const title = document.createElement('h2');
title.textContent = item.title;
title.style.textAlign = 'center';
if(index==0) slide.classList.add('active');
const div = document.createElement('div');
div.innerHTML = item.html;
slide.append(title);
slide.append(div);
slide.style.backgroundColor = item.back;
slide.style.color = item.color;
slider.append(slide);
})
}
JSON file
[
{
"title": "slide 1",
"html": "<h1>Laurence</h1>",
Laurence Svekis https://basescripts.com/
21
"back": "purple",
"color": "white"
},
{
"title": "slide 2",
"html": "<h1>Svekis</h1>",
"back": "blue",
"color": "white"
}, {
"title": "slide 4",
"html": "<h1>Svekis</h1>",
"back": "blue",
"color": "white"
},
{
"title": "slide 3",
"html": "<h1>JavaScript</h1>",
"back": "yellow",
"color": "black"
}
]
Fetch can be used to connect to external files, like JSON and return the
results of those data files into JavaScript code. The data needs time to load,
that is why promises are used to handle the data once it's ready and
returned from the endpoint. Using async and await in the function can set
up the promise to wait until a response is returned. Fetch can do the same
with the chaining of then promises to handle the data once its arrived. You
can also use promiseAll if there are multiple files that need to load data into
one object. Once all the data is ready then the file contents can be used in
the code and output on the page.
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class="main">
</div>
<script src="app6.js"></script>
</body>
</html>
JavaScript Code
btn1.onclick = fetchNow;
btn2.onclick = fetchData;
btn3.onclick = fetchAllUrls;
function fetchAllUrls() {
Promise.all(urls.map(url =>
fetch(url).then(res => res.json())
)).then((data) => {
let html = '';
data.forEach((val, ind) => {
console.log(val);
html += `<div>${ind+1}. ${val.first}
${val.last}</div>`;
})
output.innerHTML = html;
});
}
function fetchAllUrls2() {
function fetchNow() {
fetch(urls[1])
.then(response => response.json())
.then(data => {
console.log(data);
output.textContent = `${data.first} ${data.last}`;
})
.catch(error => console.log(error));
JSON #1
{
"first" : "Laurence",
JSON #2
{
"first" : "Jack",
"last" : "Doe"
}
JSON #3
{
"first" : "Kim",
"last" : "Smith"
}
This exercise is designed to test and learn more about how to check for
overlap of elements that move on the page. It will demonstrate how to set
up movement of page elements, and output the values needed to calculate
the collision between two page elements.
const keyz = {
ArrowLeft:false, ArrowRight:false, ArrowUp:false,
ArrowDown:false,
KeyA:false, KeyW:false, KeyS:false, KeyZ:false,
};
5. Add event listeners on the document that listen for keydown and
keyup events. If the keys from the keyz object pressed match the
object property name, set the value to true on press down and false
on up. This can now be used for the element movement.
6. Create and Launch the mover() function which will handle page
element movement on key presses.
7. Within the mover() function add conditions to check which keys are
true, update the game object x,y for each box accordingly. Also apply
a condition to check to ensure that before the movement is allowed
that the element is within the boundaries of the main container object
element.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
<style>
.container {
position: relative;
background-color: #ddd;
width: 90vw;
margin: auto;
.box {
position: absolute;
width: 50px;
height: 50px;
left: 0;
top: 0px;
line-height: 50px;
text-align: center;
color: white;
}
.info div {
padding: 10px;
}
.game {
position: relative;
min-height: 300px;
}
</style>
</head>
<body>
<div class="container"></div>
<script src="app8.js"></script>
</body>
</html>
window.addEventListener('DOMContentLoaded', mover);
function mover() {
const dim = [gameBoard.offsetWidth - box1.offsetWidth,
gameBoard.offsetHeight - box1.offsetHeight];
//Box 1
if (keyz.ArrowRight && game.x1 < dim[0]) game.x1 +=
game.speed;
if (keyz.ArrowLeft && game.x1 > 0) game.x1 -= game.speed;
if (keyz.ArrowDown && game.y1 < dim[1]) game.y1 +=
game.speed;
//Box 2
if (keyz.KeyS && game.x2 < dim[0]) game.x2 += game.speed;
if (keyz.KeyA && game.x2 > 0) game.x2 -= game.speed;
if (keyz.KeyZ && game.y2 < dim[1]) game.y2 += game.speed;
if (keyz.KeyW && game.y2 > 0) game.y2 -= game.speed;
box2.style.left = `${game.x2}px`;
box2.style.top = `${game.y2}px`;
To check if any two elements are overlapping you need both element, x,y
height and width values. These can then be used to calculate the corners to
see overlap on the horizontal axis and overlap on the vertical axis. If both
horizontal and vertical are overlapping then there is a collision occurring
between the two elements on the page.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
<style>
.container {
position: relative;
background-color: #ddd;
width: 90vw;
margin: auto;
.box {
position: absolute;
width: 50px;
height: 50px;
left: 0;
top: 0px;
.info {
background-color: white;
padding: 5px;
text-align: center;
font-size: 1.4em;
color: white;
}
.output1{
color:black;
font-size: 0.9em;
padding:0px;
}
.blocker{
width:200px;
left:100px;
top:100px;
position:absolute;
height:100px;
background-color:yellow;
text-align:center;
line-height:100px;
font-size:4em;
}
.game {
position: relative;
min-height: 300px;
}
</style>
</head>
<body>
<div class="container"></div>
<script src="app8.js"></script>
</body>
</html>
const game = {
move: {},
x1: box1.offsetLeft,
y1: box1.offsetTop,
x2: box2.offsetLeft,
y2: box2.offsetTop,
speed: 5,
w1: box1.offsetWidth,
h1: box1.offsetHeight,
w2: box2.offsetWidth,
h2: box2.offsetHeight
};
const keyz = {
ArrowLeft: false,
ArrowRight: false,
window.addEventListener('DOMContentLoaded', mover);
function mover() {
const dim = [gameBoard.offsetWidth - box1.offsetWidth,
gameBoard.offsetHeight - box1.offsetHeight];
//Box 1
if (keyz.ArrowRight && game.x1 < dim[0]) game.x1 +=
game.speed;
if (keyz.ArrowLeft && game.x1 > 0) game.x1 -= game.speed;
//Box 2
if (keyz.KeyS && game.x2 < dim[0]) game.x2 += game.speed;
if (keyz.KeyA && game.x2 > 0) game.x2 -= game.speed;
if (keyz.KeyZ && game.y2 < dim[1]) game.y2 += game.speed;
if (keyz.KeyW && game.y2 > 0) game.y2 -= game.speed;
box2.style.left = `${game.x2}px`;
box2.style.top = `${game.y2}px`;
function col(el1,el2){
const a = el1.getBoundingClientRect();
const b = el2.getBoundingClientRect();
//console.log(a);
//const tempX = (a.x < (b.x + b.width)) && ((a.x + a.width) >
b.x);
function maker(parent,t,html,c){
const ele = document.createElement(t);
ele.innerHTML = html;
ele.classList.add(c);
return parent.appendChild(ele);
}
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
<style>
* {
box-sizing: border-box;
}
.container {
position: relative;
width: 90vw;
margin: auto;
background-color: #ddd;
min-height: 400px;
text-align: center;
Laurence Svekis https://basescripts.com/
46
overflow: hidden;
}
.message {
padding: 10px;
background-color: white;
}
.btn {
min-width: 50%;
height: 40px;
font-size: 1.4em;
border-radius: 10px;
.box {
position: absolute;
left: 0;
top: 0;
height: 50px;
width: 50px;
line-height: 30px;
text-align: center;
border: 1px solid white;
font-size: 1.5em;
color: white;
opacity: 0.5;
.box:hover {
cursor: pointer;
border-color: red;
}
.active {
border-color: black;
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
</div>
<script src="app7.js"></script>
</body>
</html>
function init(){
for(let i=0;i<game.num;i++){
const ele = maker(main,'div',i+1,'box');
ele.style.backgroundColor =
'#'+Math.random().toString(16).slice(2,8);
ele.onclick = dropper;
}
}
function mover(){
const actives = document.querySelectorAll('.active');
actives.forEach((ele)=>{
console.log(ele.offsetTop);
let y = ele.offsetTop + game.speed;
if(y > 400){
ele.classList.remove('active');
}
ele.style.top = y + 'px';
})
game.ani = requestAnimationFrame(mover);
}
function dropper(e){
console.log(this);
function startGame(){
btn1.style.display = 'none';
message.textContent = 'Game in Play';
mover();
}
function maker(parent,t,html,c){
const ele = document.createElement(t);
ele.innerHTML = html;
ele.classList.add(c);
return parent.appendChild(ele);
}
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
<style>
* {
box-sizing: border-box;
}
Laurence Svekis https://basescripts.com/
52
.container {
position: relative;
width: 90vw;
margin: auto;
border:1px solid #ddd;
text-align: center;
}
.gameboard {
position: relative;
background-color: #ddd;
min-height: 400px;
}
.message {
padding: 10px;
background-color: white;
}
.btn {
min-width: 50%;
height: 40px;
font-size: 1.4em;
border-radius: 10px;
}
.paddle {
position: absolute;
left: 0;
.box:hover {
cursor: pointer;
border-color: red;
}
.active {
border-color: black;
opacity: 1;
}
<body>
<div class="container">
</div>
<script src="app7.js"></script>
</body>
</html>
function init() {
for (let i = 0; i < game.num; i++) {
const ele = maker(gameboard, 'div', i + 1, 'box');
ele.style.backgroundColor = '#' +
Math.random().toString(16).slice(2, 8);
ele.onclick = dropper;
ele.style.left = Math.floor(Math.random() * (game.width -
50)) + 'px';
}
}
function mover() {
const actives = document.querySelectorAll('.active');
actives.forEach((ele) => {
let y = ele.offsetTop + game.speed;
ele.style.top = y + 'px';
if (y > 400) {
ele.classList.remove('active');
ele.style.left = Math.floor(Math.random() *
(game.width - 50)) + 'px';
ele.style.top = '0px';
}
const poff = paddle.offsetTop ;
})
let paddleY = paddle.offsetLeft + (game.pspeed * paddle.val);
if (paddleY > game.width - 100 || paddleY < 0) {
paddle.val *= -1;
}
paddle.style.left = paddleY + 'px';
if (game.play) {
game.ani = requestAnimationFrame(mover);
} else {
cancelAnimationFrame(game.ani);
}
function dropper(e) {
console.log(this);
this.classList.add('active');
}
function startGame() {
game.play = true;
btn1.style.display = 'none';
gameboard.style.display = 'block';
message.textContent = 'Game in Play';
mover();
}
<!DOCTYPE html>
<html>
<head>
.container {
position: relative;
width: 90vw;
margin: auto;
border: 1px solid #ddd;
text-align: center;
}
.gameboard {
position: relative;
background-color: #ddd;
min-height: 400px;
}
.message {
padding: 10px;
background-color: white;
font-size: 1.5em;
}
.btn {
min-width: 50%;
.paddle {
position: absolute;
left: 0;
top: 380px;
height: 20px;
width: 100px;
background-color: black;
}
.box {
position: absolute;
left: 0;
top: 0px;
height: 50px;
width: 50px;
line-height: 30px;
text-align: center;
border: 1px solid white;
font-size: 1.5em;
color: white;
opacity: 0.5;
.box:hover {
cursor: pointer;
border-color: red;
}
.active {
border-color: black;
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
</div>
<script src="app7.js"></script>
</body>
</html>
function init() {
for (let i = 0; i < game.num; i++) {
const ele = maker(gameboard, 'div', i + 1, 'box');
ele.style.backgroundColor = '#' +
Math.random().toString(16).slice(2, 8);
ele.onclick = dropper;
ele.speedVal = Math.floor(Math.random() * 1) + 1;
ele.style.left = Math.floor(Math.random() * (game.width -
50)) + 'px';
}
}
//game.play =false;
}
})
let paddleY = paddle.offsetLeft + (game.pspeed * paddle.val);
if (paddleY > game.width - 100 || paddleY < 0) {
paddle.val *= -1;
}
paddle.style.left = paddleY + 'px';
if (game.play) {
game.ani = requestAnimationFrame(mover);
} else {
cancelAnimationFrame(game.ani);
}
function dropper(e) {
console.log(this);
function startGame() {
game.play = true;
game.score = 0;
init();
btn1.style.display = 'none';
gameboard.style.display = 'block';
message.textContent = 'Click the boxes Hit the paddle.';
mover();
}
How to send an email from a HTML form, using Google Apps Script and
JavaScript. Front-end code to send emails from html forms.
1. Add HTML input fields for the user to be able to enter information.
Apply CSS styling as needed to style your form fields
2. Using JavaScript select the input fields as JavaScript variables
3. Create an event that invokes a function named submitter() when the
form submit button is clicked
4. Using e.preventDefault(); to prevent the default action of the form
submission to prepare for AJAX.
5. Add conditions on the input field values, set up a variable to add
content to if errors are caught.
6. If errors are caught in the conditions, output them in a new element
that gets created with JavaScript.
7. Set a timeout to remove the error element and reset the input field
border colors back to default.
8. Create an object the contains all the form input data with property
names that match the data.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
<style>
*{
box-sizing: border-box;
}
label {
display: block;
font-family: Arial, Helvetica, sans-serif;
font-size: 0.8em;
padding-top: 15px;
}
.myForm {
width: 90%;
margin: auto;
border: 1px solid #ddd;
padding: 10px;
background-color: #eee;
}
#myForm input,
textarea {
input[type="submit"] {
background-color: black;
color: white;
text-transform: capitalize;
font-size: 1.2em;
border-radius: 10px;
}
</style>
</head>
<body>
<div class="myForm">
<form id="myForm">
<h1>Send Message</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email">
</div>
</div>
<input type="submit" value="send message">
</form>
</div>
<script src="app3.js"></script>
</body>
</html>
JavaScript Code
function submitter(e) {
console.log('submitted');
e.preventDefault();
let message = '';
} else {
const myObj = {
name: myName.value,
email: myEmail.value,
message: myMessage.value
};
console.log(myObj);
}
}
g******[email protected]
Laurence Svekis 2 m Hello World Working ????/ success
g******[email protected]
Laurence Svekis 2 m Hello World Working ????/ success
g******[email protected]
Laurence Svekis3333 om Hello World NEW success
Exercise : Update the fetch method to POST, include the form field data as
an object in the POST request body contents. Create the Google Apps Script
endpoint using a webapp to receive the GET and POST request data from the
AJAX request from JavaScript.
function doGet(e) {
return
ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentSe
rvice.MimeType.JSON);
}
function tester() {
const id = '1csURUCONXy*****@M-c0';
const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
const sheetdata = ss.getDataRange().getValues();
const str = '{"name":"Laurence
Svekis","email":"gapps*****@.com","message":"Hello
World","status":"success"}';
const json = JSON.parse(str);
Logger.log(json);
Logger.log(sheetdata[0]);
const holder = [];
function doPost(e) {
const id = '1csUR***c0';
const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
const sheetdata = ss.getDataRange().getValues();
const json = JSON.parse(e.postData.contents);
json.status = 'success';
const holder = [];
sheetdata[0].forEach((heading, index) => {
if (json[heading]) holder[index] = (json[heading]);
})
ss.appendRow(holder);
json.rowval = ss.getLastRow();
return
ContentService.createTextOutput(JSON.stringify(json)).setMimeType(Content
Service.MimeType.JSON);
}
function submitter(e) {
console.log('submitted');
e.preventDefault();
let message = '';
if (myName.value.length < 5) {
myName.style.borderColor = 'red';
message += `<br>Name needs to be 5 characters`;
}
if (myEmail.value.length < 5) {
myEmail.style.borderColor = 'red';
message += `<br>Email is missing`;
}
if (message) {
const div = document.createElement('div');
div.innerHTML = message;
div.style.color = 'red';
} else {
const myObj = {
name: myName.value,
email: myEmail.value,
message: myMessage.value
};
addSendMail(myObj);
}
}
function addSendMail(data){
console.log(data);
fetch(url,{
method:'POST',
body:JSON.stringify(data)
})
.then(res => res.json())
.then(json =>{
console.log(json);
})
}
function doPost(e) {
const id = '1csURUCONX****cR7gM-c0';
const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
const sheetdata = ss.getDataRange().getValues();
const json = JSON.parse(e.postData.contents);
json.status = 'success';
const holder = [];
sheetdata[0].forEach((heading, index) => {
if (json[heading]) holder[index] = (json[heading]);
})
ss.appendRow(holder);
json.rowval = ss.getLastRow();
return
ContentService.createTextOutput(JSON.stringify(json)).setMimeType(Content
Service.MimeType.JSON);
}
function tester() {
const id = '1csURUC*****@gM-c0';
function doGet(e) {
return
ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentSe
rvice.MimeType.JSON);
}
Exercise : Update the Google Apps Script to send emails to the user's email
address in response to the web form submission, send a second email to
your email when the form data is submitted with the form field information.
function sendMyEmail(data) {
let emailBody = `<div>Name ${data.name}</div>`;
emailBody += `<div>Email ${data.email}</div>`;
emailBody += `<div>Message ${data.message}</div>`;
MailApp.sendEmail({
to: 'g*****@@gmail.com',
subject: 'NEW Web Form Email',
htmlBody: emailBody
});
if (validateEmail(data.email)) {
let repHTML = `<h2>Thank you ${data.name}</h2>`;
repHTML += `<div>We will respond shortly. Message received ID
${data.rowval}</div>`;
MailApp.sendEmail({
to: data.email,
subject: 'Thank you for your email',
htmlBody: repHTML
});
return true;
Laurence Svekis https://basescripts.com/
83
} else {
return false;
}
}
function validateEmail(email) {
const re = /\S+@\S+\.\S+/;
return re.test(email);
}
function testEmail() {
const val = {
email: 'gapps*****@gmail.com',
name: 'tester',
message: 'Hello World',
rowval: 50
}
Logger.log(sendMyEmail(val));
}
Update JavaScript to manage the submission of the data and provide user
feedback
JAVASCRIPT
function submitter(e) {
console.log('submitted');
e.preventDefault();
subBtn.disabled = true;
Laurence Svekis https://basescripts.com/
85
let message = '';
if (myName.value.length < 5) {
myName.style.borderColor = 'red';
message += `<br>Name needs to be 5 characters`;
}
if (myEmail.value.length < 5) {
myEmail.style.borderColor = 'red';
message += `<br>Email is missing`;
}
if (message) {
const div = document.createElement('div');
div.innerHTML = message;
div.style.color = 'red';
myForm.append(div);
setTimeout(() => {
div.remove();
myName.style.borderColor = '';
myEmail.style.borderColor = '';
}, 5000);
subBtn.disabled = false;
} else {
const myObj = {
name: myName.value,
email: myEmail.value,
message: myMessage.value
};
myForm.style.display = 'none';
addSendMail(myObj);
}
function addSendMail(data){
console.log(data);
const repDiv = document.createElement('div');
repDiv.textContent = 'Waiting.....';
main.append(repDiv);
fetch(url,{
method:'POST',
body:JSON.stringify(data)
})
.then(res => res.json())
.then(json =>{
console.log(json);
if(json.rowval){
repDiv.textContent = `Message Sent Your ID is ${json.rowval}`;
}else{
repDiv.remove();
subBtn.disabled = false;
myForm.style.display = 'block';
}
})
}
function addSendMailGET(data){
const url1 = url + '?id=100';
fetch(url1)
.then(res => res.json())
function doPost(e) {
const id = '1csURUCO********';
const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
const sheetdata = ss.getDataRange().getValues();
const json = JSON.parse(e.postData.contents);
json.status = 'success';
const holder = [];
sheetdata[0].forEach((heading, index) => {
if (json[heading]) holder[index] = (json[heading]);
})
ss.appendRow(holder);
json.rowval = ss.getLastRow();
json.result = sendMyEmail(json);
return
ContentService.createTextOutput(JSON.stringify(json)).setMimeType(Content
Service.MimeType.JSON);
}
function sendMyEmail(data) {
let emailBody = `<div>Name ${data.name}</div>`;
emailBody += `<div>Email ${data.email}</div>`;
function validateEmail(email) {
const re = /\S+@\S+\.\S+/;
return re.test(email);
}
function testEmail() {
const val = {
email: 'gappsc*****@gmail.com',
function tester() {
const id = '1csURU*******gM-c0';
const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
const sheetdata = ss.getDataRange().getValues();
const str = '{"name":"Laurence
Svekis","email":"gapp*******@gmail.com","message":"Hello
World","status":"success"}';
const json = JSON.parse(str);
Logger.log(json);
Logger.log(sheetdata[0]);
const holder = [];
sheetdata[0].forEach((heading, index) => {
if (json[heading]) holder[index] = (json[heading]);
})
Logger.log(holder);
ss.appendRow(holder);
}
function doGet(e) {
return
ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentSe
rvice.MimeType.JSON);}