Store a string in local storage - javascript

First of all,i'm sorry for my english. I've created a simple wishlist system for an online store i'm building using jquery. But now i don't know how to store the items in local storage so the user can see them the next time he visit the store. I'm new to jquery and my coding abilities are very poor. Here's what i built:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
body{background:#333;font-family:"Open sans", sans-serif;font-size:100%;text-align:center;font-size:62.5%;}
button{padding:5px 20px;border-radius:4px;margin:10px auto;border:0;background-color:#fff;font-weight:600;cursor:pointer;color:#c12267;}
#wish_list{margin:100px auto;min-height:300px;width:100%;background:#fff;}
#wish_list .wish_list_heading{margin:0;color:#fff;height:30px;background-color:#c12267;overflow:hidden;padding:5px;font-weight:600;}
#wish_list_item{width:100%;text-align:center;border-spacing:0px;border-collapse:separate;}
.wishlist-item{position:relative;clear:both;width:100%;margin:2px 0;padding:0;float:left;display:block;height:80px;border-bottom:1px solid #EEE;}
.w-premove{position:absolute;width:20px;display:block;height:20px;top:30px;left:0;text-align:center;font-weight:900;font-size:140%;line-height:20px;color:red;}
.w-pimage{top:0;left:25px;width:75px;height:25px;display:block;position:absolute;}
.w-pimage img{width:100%;}
.w-pname{top:5px;left:100px;width:calc(100% - 100px);width:-o-calc(100% - 100px);width:-webkit-calc(100% - 100px);width:-moz-calc(100% - 100px);height:40px;padding:0;text-align:left;font-size:140%;font-weight:600;line-height:1em;position:absolute;}
.w-pname a{text-decoration:none;color:#333;}
.w-price{top:50px;left:100px;height:20px;width:75px;color:#c12267;font-weight:600;font-size:150%;text-align:center;line-height:20px;display:block;position:absolute;}
</style>
</head>
<body>
<button class='wishlist' product_name='Product 1' product_id='product1' product_link="PRODUCT PAGE URL" product_price='90' product_image="IMAGE LINK">DESEJAR</button>
<div id='wish_list'>
<p class="wish_list_heading">
<span id='listitem'>0</span>
<span id='p_label'>Product</span>
</p>
<table id='wish_list_item' border='0'></table>
</div>
<script type='text/javascript'>
var wish_list = new Array();
jQuery(function(){
jQuery(".wishlist").on("click",function(){
$data = "";
$product_id = jQuery(this).attr("product_id");
$product_name = jQuery(this).attr("product_name");
$prduct_price = jQuery(this).attr("product_price");
$product_link = jQuery(this).attr("product_link");
$product_image = jQuery(this).attr("product_image");
if(jQuery.inArray($product_id,wish_list)==-1){
$product_str = "<tr class='wishlist-item' id='list_id_"+$product_id+"'><td class='w-premove' wpid='"+$product_id+"'>x</td><td class='w-pimage'><img src='"+$product_image+"' /></td><td class='w-pname'><a href='"+$product_link+"'>"+$product_name+"</a></td><td class='w-price'>"+$prduct_price+"€</td></tr>";
jQuery("#wish_list_item").append($product_str);
wish_list.push($product_id);
}
count_items_in_wishlist_update();
});
jQuery("#wish_list_item").on("click",".w-premove",function(){
$product_id = jQuery(this).attr("wpid");
jQuery("#list_id_"+$product_id).remove();
wish_list = jQuery.grep( wish_list, function( n, i ) {
return n != $product_id;
});
count_items_in_wishlist_update();
});
});
function count_items_in_wishlist_update(){
jQuery("#listitem").html(wish_list.length);
if(wish_list.length>1){
jQuery("#p_label").html("Products");
}else{
jQuery("#p_label").html("Product");
}
}
</script>
</body>
</html>`
Is it possible to store the strings $product_str in local Storage and present them when the user comes back? How can this be done?

Use
localStorage.setItem("lastname", "Smith");
to set a value with lastname as key and "Smith" as value
Use,
var result = localStorage.getItem("lastname");
to get the value of key lastname
The localStorage object stores the data with no expiration date.

You might want to look into cookies.

Related

In Google Apps Script, How to prevent multiple submission of form data by reloading the HTML returned by doPost()?

I created a web form using Google Apps Script, where form visitors would see result.html after data submission. However, the data may be submitted multiple times if visitors reload the result.html by pressing F5, Ctrl + R, ignoring the alert of resubmission. The same concern has already been posted here, and I tried implementing one of the solutions for that, but in vain.
I have now four files in the same project of Google Apps Script:
index.html that produces the form
JavaScript.html that defines functions used in index.html
result.html that is presented after the form submission
code.gs that shows the form by doGet(), and processes the submitted data and presents result.html by doPost(). include() defined in this file enables to input JavaScript.html into index.html
The solution I have tried is adding the following JavaScript code result.html. I also add that to JavaScript.html so that the code is to be executed in index.html, too.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
However, the resubmission still occurs when I reload the result.html even after I added that code to both result.html and index.html. What am I missing?
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!-- <?!= include("css"); ?> -->
</head>
<body onload="addOptions()"> <!--Execute addOptions function immediately after a page has been loaded-->
<form class="" action="<?!= getScriptUrl(); ?>" method="post" onSubmit="document.getElementById('submit').disabled=true;">
<div>
<h1 id="Question">
Choose either cheesecake or chocolate cake.
</h1>
<select id="dropdownList" name="cake" class="form-control">
</select>
</div>
<div class="form-submit">
<input type="submit" name="" value="Submit">
</div>
</form>
</body>
<?!= include('JavaScript') ?>
</html>
JavaScript.html
<script>
function addOptions() {
/*This will call server-side Apps Script function getAvailableExps and if it is successful,
it will pass the return value to function addListValues which will add options to the drop down menu*/
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(addListValues)
.getAvailableExps();
}
function addListValues(values) {
//Add options to drop down menu using the values of parameter 'values'.
for (var i = 0; i < values.length; i++) {
var option = document.createElement("option");
option.text = values[i][0];
option.value = values[i][0];
var select = document.getElementById("dropdownList");
select.appendChild(option);
}
}
function onFailure(err) {
alert('Error: ' + err.message);
}
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
result.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<base />
<title>Thank you for your order!</title>
<!-- <?!= include('css'); ?> -->
</head>
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
<body>
<p>
Don't forget what you've ordered!
</p>
</body>
</html>
code.gs
var sheetID = "............................................";
var inventory_sheet = "Inventory";
function doGet(){
return HtmlService.createTemplateFromFile("index").evaluate();
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
Logger.log(url);
return url;
}
function doPost(e){
var ss = SpreadsheetApp.openById(sheetID);
var sh = ss.getSheets()[0];
sh.appendRow([String(e.parameters.cake)]);
//update Inventory
var inventory = ss.getSheetByName(inventory_sheet);
var row = inventory.createTextFinder(e.parameters.cake).findNext().getRow();
var range = inventory.getRange(row, 2);
var data = range.getValue();
range.setValue(parseInt(data - 1))
return HtmlService.createTemplateFromFile("result").evaluate();
}
function getAvailableExps(){
var inventory = SpreadsheetApp.openById(sheetID).getSheetByName(inventory_sheet);
var data = inventory.getRange(2, 1, 2, 2).getValues();
var filtered = data.filter(arr => arr[1] > 0 || arr[1] != ''); //remove exp to array if quantity is 0 or empty
return filtered;
}
In your situation, how about checking the submit using PropertiesService? When your script is modified, it becomes as follows.
Modified script:
In this modification, 2 functions of doGet and doPost of code.gs are modified.
doGet
function doGet() {
PropertiesService.getScriptProperties().setProperty("key", "sample");
return HtmlService.createTemplateFromFile("index").evaluate();
}
doPost
function doPost(e) {
var p = PropertiesService.getScriptProperties();
if (p.getProperty("key") == "sample") {
var ss = SpreadsheetApp.openById(sheetID);
var sh = ss.getSheets()[0];
sh.appendRow([String(e.parameters.cake)]);
//update Inventory
var inventory = ss.getSheetByName(inventory_sheet);
var row = inventory.createTextFinder(e.parameters.cake).findNext().getRow();
var range = inventory.getRange(row, 2);
var data = range.getValue();
range.setValue(parseInt(data - 1))
p.deleteProperty("key");
}
return HtmlService.createTemplateFromFile("result").evaluate();
}
When you access to your Web Apps, sample is stored by setProperty("key", "sample") in doGet(). And, when the HTML form is submitted, the PropertiesService is checked in doPost(e). When sample is existing, the data is put, and the PropertiesService is cleared. By this, even when the submitted page is reopened, the PropertiesService is not existing. By this, the resubmitted can be avoided.
Reference:
Properties Service

Javascript Localstorage: Comparing input value with value stored in array in localstorage

My purpose is to check if value entered by user in the input field is already available in an array stored in the localstorage. If yes, print the array if not add the new value in the storage. I am getting my array back on button click but the code isn't working correctly. The output is:
["hh", "try", "vogue", "vogue", "try2", "try2", "try2", "try2"]
Above are the entered values which are getting added repetitively. I know it's a stupid issue but have least experience with handling arrays in localstorage. Any help would be appreciated. (I tried the solutions provided in similar questions on stackoverflow but no luck)
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
var storedNames;
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
for(i=0; i <storedNames.length; i++) {
if(enteredValue === storedNames[i]) {
console.log("value Exist!!");
console.log(storedNames[]);
}
else {
console.log("in else");
coupons.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(coupons));
storedNames = JSON.parse(localStorage.getItem("coupons"));
}
}
});
</script>
</body>
</html>
You would like to push the names if it doesn't exist in the stored names. Refer attached code.
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
var storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
if (storedNames.includes(enteredValue)) {
console.log("value Exist!!");
console.log(storedNames);
} else {
console.log("in else");
storedNames.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(storedNames));
}
});
</script>
</body>
</html>

PHP Javascript HTML

I'm having trouble finding my exact question so I'll post it here. I'm working with an oracle database and I'm linking it to an HTML website via javascript and php. I got the php file to display properly. Essentially what's supposed to happen is I have 4 button, each one generates a specific query and displays the results in a new html page. It's a movie database, so one of our queries is Budgets vs. Genre. It works the way I have it, but it doesn't generate it via the html file, it displays the PHP file. My goal is to retrieve the output of the PHP file via javascript and set it to the HTML file for output. I'm new to php and javascript working together, so maybe someone can tell me what's happening here and what needs to be changed for it to work properly. I got the javascript code from oracles website for connecting a database to a website.
Here's my PHP first:
<?php
// Connect to the database=
$c = oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
print '<table border="1"><tr><th>Rank</th><th>Title</th><th>Budget</th>';
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], 'budget' => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
and here's my javascript :
$(function() {
$("button#genBudg").click(function() {
$.getJSON("ajaxCopy.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
window.location.replace("generate_report.html");
});
});
});
and here's my html:
(select_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Reports</h2>
<div class="input_options">
<div>
<button type="button" class="option" style="padding:10px 30px" id="genBudg">Genre vs Budget</button>
<button type="button" class="option" style="padding:10px 30px">Rating vs Budget</button>
</div>
<div>
<button type="button" class="option" style="padding:10px 30px">Budget vs Gross</button>
<button type="button" class="option" style="padding:10px 30px">Actor vs Rating</button>
</div>
</div>
<script src ="jquery-1.4.4.js"></script>
<script src="movies.js"></script>
</body>
</html>
(generate_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Name of report</h2>
<div id = "bud_gro"></div>
<script src="movies.js"></script>
<script src="jquery-1.4.4.js"></script>
</body>
</html>
As discussed, it may be better to pass JSON data back to an AJAX call and build the table based on the results. This might look like this:
PHP
<?php
// Connect to the database= oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
$table = array();
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], "budget" => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
You can then make use of a jQuery solution like so:
HTML
<button id="getReport">
Get Report
</button>
<h2>Name of report</h2>
<p id="bud_gro"></p>
JavaScript
$(function() {
$("button#getReport").click(function() {
$.getJSON("ajax.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
});
});
});

How to use an element property to pass a variable from Javascript

I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets

Converting from NATIVE to IFRAME Sandbox with Enter Key Submit

I have a similar problem to this post when trying to convert my apps script web app to use IFRAME Sandbox. I have converted to 'input = "button"' as suggested.
My web app is a simple form for students to use to sign in and out of a school library. The idea for the app is for it to be as easy as possible for students to use. Students should enter their id number and be able to either click the submit button or hit the enter key. Their ID is then validated before being stored in a spreadsheet and they get a message back saying thanks for signing in or out, or please enter a valid ID Number. Then focus should return to the text box and be cleared, ready for the next student to enter their id.
I had it working as described above using NATIVE mode. When I tried to convert it to IFRAME mode, clicking the button works, but if you hit the enter key everything just disappears and no data goes to the spreadsheet. How can I get hitting the enter key to work the same as clicking the submit button?
index.html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<h3>Please Sign In & Out</h3>
<div id="box" class="frame">
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
<input type="text" name="myID" id="myID" placeholder="Enter your student ID" autocomplete="off">
<input type="button" value="Submit" onmouseup="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
</form>
<span id="thank_you" hidden="true"></span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?!= include('javascript'); ?>
</body>
</html>
javascript.html code:
<script>
function updateInfo(ret){
if(ret[0]){
$( "#thank_you" ).removeClass("error");
$( "#thank_you" ).addClass("valid");
}
else{
$( "#thank_you" ).removeClass("valid");
$( "#thank_you" ).addClass("error");
}
$( "#thank_you" ).text(ret[1]);
$( "#thank_you" ).show("slow");
$( "#signSheet" )[0].reset();
$( "#myID" ).focus();
console.log(ret);
}
</script>
Code.gs code:
//spreadsheet key is needed to access the spreadsheet.
var itemSpreadsheetKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//Open the spreadsheet and get the sheet objects
var openedSS = SpreadsheetApp.openById(itemSpreadsheetKey);
var studentList = openedSS.getSheetByName("Student List");//Spreadsheet must match with sheet name
var studentRecord = openedSS.getSheetByName("Sign In-Out Record");
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Sign In/Out Sheet')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function include(filename) {
Logger.log('enter include');
Logger.log(filename);
var html = HtmlService.createHtmlOutputFromFile(filename).getContent();
Logger.log(html);
return html;
}
function validateID(form){
var idNum = form.myID;
var valid = false;
var numIdList = studentList.getLastRow()-1; //-1 is to exclude header row
//get the item array
var idArray = studentList.getRange(2,1,numIdList,1).getValues();
i= idArray.length;
while(i--){
if(idArray[i][0]==idNum & idNum!='') {
valid=true;
break;
}
}
if(valid)
return [1, updateRecord(idNum)];
else return [0, "ID number " + idNum + " not recognized. Please enter a valid ID number."];
}
function updateRecord(idNum){
studentRecord.appendRow([idNum]);
var formulas = studentRecord.getRange("B2:D2").getFormulasR1C1();
var lRow = studentRecord.getLastRow();
var range = studentRecord.getRange(lRow, 2, 1, 3);
range.setFormulas(formulas);
var vals = range.getValues();
var now = new Date();
studentRecord.getRange(lRow, 5, 1, 1).setValue(now);
now = Utilities.formatDate(now, "EST", "HH:MM a");
idNum = "Thanks " + vals[0][0] + ", you have signed " + vals[0][2] + " at " + now;
return idNum;
}
Update: I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This solved the the problem for me with a little more tweaking to parts of index.html and Code.gs
I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This listens for the enter key and sends the value of the text field to the apps script function. In this case I didn't need to use `event.preventDefault();'
Then I had to adjust the button's onmouseup function to take this.parentNode.myID and change my apps script function to take a value instead of a form object.
You must remove the onsubmit attribute from the <form> tag:
Currently you have:
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
Change it to this:
<form id="signSheet">
You already have a call to google.script.run in your button, so leave that.

Categories

Resources