I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
I am a beginner in google app script. I am creating resident payment system where if the user increases the number of paid by one I want to add the a new row in sales worksheet in google sheet with new invoice number and the address of the specific user (which means lets say the user's address is 16, Jalan Sanggul 4 so I want to add it to the worksheet under the address column). I have attached few images and link to my google appscript coding here to explain myself better. I really hope that you guys can help me with it. Thank you guys.
Link to google app script (There is few numbers of html there so give the link ) - https://script.google.com/d/1NvaCQBc1fZWT7Y5cdvSi_XVL2-ytRVDP41AgY-btOA_MYrd8vcQK4fb_/edit?usp=sharing
Link to google sheet - https://docs.google.com/spreadsheets/d/1GO_kQVuXBtBZSKreNSvYu_kTRQMuL7YN5VXd14zgMig/edit?usp=sharing
[Payment Data Image (1) - Google Sheet]1
[Payment Data Image (2)- Google Sheet]2
Code.gs
function doGet(request) {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle("Admin Login")
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Check Login
function checkLogin(loginUsername, loginPassword) {
var url = 'https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1151242353';
var ss= SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("Admin Data");
var getLastRow = webAppSheet.getLastRow();
var found_record = '';
for(var i = 1; i <= getLastRow; i++)
{
if(webAppSheet.getRange(i, 1).getValue() == loginUsername &&
webAppSheet.getRange(i, 2).getValue() == loginPassword)
{
found_record = 'TRUE';
}
}
if(found_record == '')
{
found_record = 'FALSE';
}
return found_record;
}
/*--------------------------------------------------------------------------------------------------------
---------------GLOBAL VARIABLES---------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
*/
function globalVariables(){
var varArray = {
spreadsheetId : '1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8', //** CHANGE !!!
admindataRage : 'Admin Data!A2:B', //** CHANGE !!!
adminidRange : 'Admin Data!A2:A', //** CHANGE !!!
adminlastCol : 'B', //** CHANGE !!!
admininsertRange : 'Admin Data!A1:B1', //** CHANGE !!!
adminsheetID : '1151242353',
dataRage : 'USERNAMES!A2:H', //** CHANGE !!!
idRange : 'USERNAMES!A2:A', //** CHANGE !!!
lastCol : 'H', //** CHANGE !!!
insertRange : 'USERNAMES!A1:H1', //** CHANGE !!!
sheetID : '0'
};
return varArray;
}
/*-------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------FUCNTION FOR ADMIN CRUD PART-----------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
/* PROCESS FORM */
function processAdminForm(formObject){
if(formObject.admin_uname && checkAdminID(formObject.admin_uname)){//Execute if form passes an ID and if is an existing ID
updateAdminData(getAdminFormValues(formObject),globalVariables().spreadsheetId,getAdminRangeByID(formObject.admin_uname)); // Update Data
}else{ //Execute if form does not pass an ID
appendAdminData(getAdminFormValues(formObject),globalVariables().spreadsheetId,globalVariables().admininsertRange); //Append Form Data
}
return getAdminLastTenRows();//Return last 10 rows
}
/* GET FORM VALUES AS AN ARRAY */
function getAdminFormValues(formObject){
/* ADD OR REMOVE VARIABLES ACCORDING TO YOUR FORM*/
if(formObject.admin_uname && checkAdminID(formObject.admin_uname)){
var values = [[
//formObject.username.toString(),
formObject.admin_uname,
formObject.admin_pw]];
}else{
var values = [[
//new Date().getTime().toString(),//https://webapps.stackexchange.com/a/51012/244121
formObject.admin_uname,
formObject.admin_pw]];
}
return values;
}
/* CREATE/ APPEND DATA */
function appendAdminData(values, spreadsheetId,range){
var valueRange = Sheets.newRowData();
valueRange.values = values;
var appendRequest = Sheets.newAppendCellsRequest();
appendRequest.adminsheetID = spreadsheetId;
appendRequest.rows = valueRange;
var results = Sheets.Spreadsheets.Values.append(valueRange, spreadsheetId, range,{valueInputOption: "RAW"});
}
/* READ DATA */
function readAdminData(spreadsheetId,range){
var result = Sheets.Spreadsheets.Values.get(spreadsheetId, range);
return result.values;
}
/* UPDATE DATA */
function updateAdminData(values,spreadsheetId,range){
var valueRange = Sheets.newValueRange();
valueRange.values = values;
var result = Sheets.Spreadsheets.Values.update(valueRange, spreadsheetId, range, {
valueInputOption: "RAW"});
}
/*DELETE DATA*/
function deleteAdminData(ID){
//https://developers.google.com/sheets/api/guides/batchupdate
//https://developers.google.com/sheets/api/samples/rowcolumn#delete_rows_or_columns
var startIndex = getAdminRowIndexByID(ID);
var deleteRange = {
"sheetId" : globalVariables().adminsheetID,
"dimension" : "ROWS",
"startIndex" : startIndex,
"endIndex" : startIndex+1
}
var deleteRequest= [{"deleteDimension":{"range":deleteRange}}];
Sheets.Spreadsheets.batchUpdate({"requests": deleteRequest}, globalVariables().spreadsheetId);
return getAdminLastTenRows();//Return last 10 rows
}
/* CHECK FOR EXISTING ID, RETURN BOOLEAN */
function checkAdminID(ID){
var idList = readAdminData(globalVariables().spreadsheetId,globalVariables().adminidRange,).reduce(function(a,b){return a.concat(b);});
return idList.includes(ID);
}
/* GET DATA RANGE A1 NOTATION FOR GIVEN ID */
function getAdminRangeByID(id){
if(id){
var idList = readAdminData(globalVariables().spreadsheetId,globalVariables().adminidRange);
for(var i=0;i<idList.length;i++){
if(id==idList[i][0]){
return 'Admin Data!A'+(i+2)+':'+globalVariables().adminlastCol+(i+2);
}
}
}
}
/* GET RECORD BY ID */
function getAdminRecordById(id){
if(id && checkAdminID(id)){
var result = readAdminData(globalVariables().spreadsheetId,getAdminRangeByID(id));
return result;
}
}
/* GET ROW NUMBER FOR GIVEN ID */
function getAdminRowIndexByID(id){
if(id){
var idList = readAdminData(globalVariables().spreadsheetId,globalVariables().adminidRange);
for(var i=0;i<idList.length;i++){
if(id==idList[i][0]){
var rowIndex = parseInt(i+1);
return rowIndex;
}
}
}
}
/*GET LAST 10 RECORDS */
function getAdminLastTenRows(){
var lastRow = readAdminData(globalVariables().spreadsheetId,globalVariables().admindataRage).length+1;
if(lastRow<=11){
var range = globalVariables().admindataRage;
}else{
var range = 'Admin Data!A'+(lastRow-9)+':'+globalVariables().adminlastCol;
}
var lastTenRows = readAdminData(globalVariables().spreadsheetId,range);
return lastTenRows;
}
/* GET ALL RECORDS */
function getAdminAllData(){
var data = readAdminData(globalVariables().spreadsheetId,globalVariables().admindataRage);
return data;
}
/*-------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------FUCNTION FOR RESIDENT CRUD PART-----------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
/* PROCESS FORM */
function processForm(formObject){
if(formObject.username && checkID(formObject.username)){//Execute if form passes an ID and if is an existing ID
updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.username)); // Update Data
}else{ //Execute if form does not pass an ID
appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange); //Append Form Data
}
return getLastTenRows();//Return last 10 rows
}
/* GET FORM VALUES AS AN ARRAY */
function getFormValues(formObject){
/* ADD OR REMOVE VARIABLES ACCORDING TO YOUR FORM*/
if(formObject.username && checkID(formObject.username)){
var values = [[
//formObject.username.toString(),
formObject.username,
formObject.housenumber,
formObject.street,
formObject.firstname,
formObject.lastname,
formObject.noOfPaid,
formObject.password,
formObject.phone]];
}else{
var values = [[
//new Date().getTime().toString(),//https://webapps.stackexchange.com/a/51012/244121
formObject.username,
formObject.housenumber,
formObject.street,
formObject.firstname,
formObject.lastname,
formObject.noOfPaid,
formObject.password,
formObject.phone]];
}
return values;
}
/* CREATE/ APPEND DATA */
function appendData(values, spreadsheetId,range){
var valueRange = Sheets.newRowData();
valueRange.values = values;
var appendRequest = Sheets.newAppendCellsRequest();
appendRequest.sheetID = spreadsheetId;
appendRequest.rows = valueRange;
var results = Sheets.Spreadsheets.Values.append(valueRange, spreadsheetId, range,{valueInputOption: "RAW"});
}
/* READ DATA */
function readData(spreadsheetId,range){
var result = Sheets.Spreadsheets.Values.get(spreadsheetId, range);
return result.values;
}
/* UPDATE DATA */
function updateData(values,spreadsheetId,range){
var valueRange = Sheets.newValueRange();
valueRange.values = values;
var result = Sheets.Spreadsheets.Values.update(valueRange, spreadsheetId, range, {
valueInputOption: "RAW"});
}
/*DELETE DATA*/
function deleteData(ID){
//https://developers.google.com/sheets/api/guides/batchupdate
//https://developers.google.com/sheets/api/samples/rowcolumn#delete_rows_or_columns
var startIndex = getRowIndexByID(ID);
var deleteRange = {
"sheetId" : globalVariables().sheetID,
"dimension" : "ROWS",
"startIndex" : startIndex,
"endIndex" : startIndex+1
}
var deleteRequest= [{"deleteDimension":{"range":deleteRange}}];
Sheets.Spreadsheets.batchUpdate({"requests": deleteRequest}, globalVariables().spreadsheetId);
return getLastTenRows();//Return last 10 rows
}
/* CHECK FOR EXISTING ID, RETURN BOOLEAN */
function checkID(ID){
var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange,).reduce(function(a,b){return a.concat(b);});
return idList.includes(ID);
}
/* GET DATA RANGE A1 NOTATION FOR GIVEN ID */
function getRangeByID(id){
if(id){
var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange);
for(var i=0;i<idList.length;i++){
if(id==idList[i][0]){
return 'USERNAMES!A'+(i+2)+':'+globalVariables().lastCol+(i+2);
}
}
}
}
/* GET RECORD BY ID */
function getRecordById(id){
if(id && checkID(id)){
var result = readData(globalVariables().spreadsheetId,getRangeByID(id));
return result;
}
}
/* GET ROW NUMBER FOR GIVEN ID */
function getRowIndexByID(id){
if(id){
var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange);
for(var i=0;i<idList.length;i++){
if(id==idList[i][0]){
var rowIndex = parseInt(i+1);
return rowIndex;
}
}
}
}
/*GET LAST 10 RECORDS */
function getLastTenRows(){
var lastRow = readData(globalVariables().spreadsheetId,globalVariables().dataRage).length+1;
if(lastRow<=11){
var range = globalVariables().dataRage;
}else{
var range = 'USERNAMES!A'+(lastRow-9)+':'+globalVariables().lastCol;
}
var lastTenRows = readData(globalVariables().spreadsheetId,range);
return lastTenRows;
}
/* GET ALL RECORDS */
function getAllData(){
var data = readData(globalVariables().spreadsheetId,globalVariables().dataRage);
return data;
}
/*GET DROPDOWN LIST */
function getDropdownList(range){
var list = readData(globalVariables().spreadsheetId,range);
return list;
}
//CODE FOR DATA SEARCH
function searchData(formObject){
var result = [];
if(formObject.searchtext){//Execute if form passes search text
var data = Sheets.Spreadsheets.Values.get(globalVariables().spreadsheetId, globalVariables().dataRage).values;
for(var i=0;i<data.length;i++){
for(var j=0;j<data[i].length;j++){
if(data[i][j].toLowerCase().search(formObject.searchtext.toLowerCase())!=-1){
result.push(data[i])
}
}
}
}
return result;
}
/* INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function getScriptURL() {
var url = ScriptApp.getService().getUrl();
return url ;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
-->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<!-- Font Awesome -->
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<?!= include('CSS'); ?> <!-- See CSS.html file -->
</head>
<body onload="createStreetDropdown()">
<div id="loginDisplay" class="loginDisplay">
<?!= include('loginDisplay'); ?>
</div>
<div style="display:none" id="dataDisplay" >
<div>
<button type="button" class="btn btn-primary" onclick="LogOut()">
Log out
</button>
<!--<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span>Log out
</button>-->
</div>
<br>
<div>
<button type="button" class="btn btn-primary" onclick="">
Admin
</button>
<button type="button" class="btn btn-primary" onclick="">
Resident
</button>
</div>
<div class="container">
<div class="row">
<div class="col-lg-6">
<?!= include('AdminForm'); ?>
<br><br>
<div id="output"></div>
</div>
<div class="col-lg-6">
<?!= include('AdminDataTable'); ?>
</div>
<!--
<div class="col-lg-12">
<?!= include('AdminDataTable'); ?>
</div>
-->
</div>
<br><br>
<hr>
<div class="row">
<div class="col-lg-12">
<?!= include('Form'); ?>
<br><br>
<div id="output"></div>
</div>
<div class="col-lg-12">
<?!= include('DataTable'); ?>
</div>
</div>
</div>
</div>
</body>
</html>
JavaScript.html
<script>
//--------Login Page----------------------------------
function LoginUser()
{
var loginUsername = document.getElementById("loginUsername").value;
var loginPassword = document.getElementById("loginPassword").value;
google.script.run.withSuccessHandler(function(output)
{
if(output == 'TRUE')
{
document.getElementById("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
}
else if(output == 'FALSE')
{
document.getElementById("errorMessage").innerHTML = "Failed to Login";
}
}).checkLogin(loginUsername, loginPassword);
}
//-------Log Out----------------------
function LogOut(){
google.script.run
.withSuccessHandler(function(url){window.open(url,"_top");})
.getScriptURL();
//var url=window.location.href
//window.open(url,'_top');
//window.open("https://script.google.com/macros/s/AKfycbyS5LJn4i6mJeMzjWWryW7TUUDeeAZtVteJdCd6lT0FPPEiCiVy/exec",'_top');
}
//----------------------------------------------------------
//---------Admin Part---------------------------------------
// Prevent forms from submitting.
function preventAdminFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener("load", adminfunctionInit, true);
//INITIALIZE FUNCTIONS ONLOAD
function adminfunctionInit(){
preventAdminFormSubmit();
getAdminLastTenRows();
};
//HANDLE FORM SUBMISSION
function handleAdminFormSubmit(formObject) {
google.script.run.withSuccessHandler(createAdminTable).processAdminForm(formObject);
document.getElementById("adminForm").reset();
}
//GET LAST 10 ROWS
function getAdminLastTenRows (){
google.script.run.withSuccessHandler(createAdminTable).getAdminLastTenRows();
}
//GET ALL DATA
function getAdminAllData(){
//document.getElementById('adminDataTable').innerHTML = "";
google.script.run.withSuccessHandler(createAdminTable).getAdminAllData();
}
//CREATE THE DATA TABLE
function createAdminTable(dataArray) {
if(dataArray){
var result = "<table class='table table-sm' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+ //Change table headings to match witht he Google Sheet
"<th scope='col'>Delete</th>"+
"<th scope='col'>Edit</th>"+
"<th scope='col'>Username</th>"+
"<th scope='col'>Password</th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
result += "<td><button type='button' class='btn btn-danger btn-xs deleteBtn' onclick='deleteAdminData(this);'>Delete</button></td>";
result += "<td><button type='button' class='btn btn-warning btn-xs editBtn' onclick='editAdminData(this);'>Edit</button></td>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('adminDataTable');
div.innerHTML = result;
document.getElementById("admin_message").innerHTML = "";
}else{
var div = document.getElementById('adminDataTable');
div.innerHTML = "Data not found!";
}
}
//DELETE DATA
function deleteAdminData(el) {
var result = confirm("Want to delete?");
if (result) {
var admin_uname = el.parentNode.parentNode.cells[2].innerHTML;
google.script.run.withSuccessHandler(createAdminTable).deleteAdminData(admin_uname);
}
}
//EDIT DATA
function editAdminData(el){
var admin_uname = el.parentNode.parentNode.cells[2].innerHTML; //https://stackoverflow.com/a/32377357/2391195
google.script.run.withSuccessHandler(populateAdminForm).getAdminRecordById(admin_uname);
}
//POPULATE FORM
function populateAdminForm(records){
document.getElementById('admin_uname').value = records[0][0];
document.getElementById('admin_pw').value = records[0][1];
document.getElementById("admin_message").innerHTML = "<div class='alert alert-warning' role='alert'>Update Record [ADMIN: "+records[0][0]+"]</div>";
}
//-----------------------------------------------------------------------
//----------------Resident Part------------------------------------------
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener("load", functionInit, true);
//INITIALIZE FUNCTIONS ONLOAD
function functionInit(){
preventFormSubmit();
getLastTenRows();
};
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
document.getElementById("myForm").reset();
}
//GET LAST 10 ROWS
function getLastTenRows (){
google.script.run.withSuccessHandler(createTable).getLastTenRows();
}
//GET ALL DATA
function getAllData(){
//document.getElementById('dataTable').innerHTML = "";
google.script.run.withSuccessHandler(createTable).getAllData();
}
//CREATE THE DATA TABLE
function createTable(dataArray) {
if(dataArray){
var result = "<table class='table table-sm' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+ //Change table headings to match witht he Google Sheet
"<th scope='col'>Delete</th>"+
"<th scope='col'>Edit</th>"+
//"<th scope='col'>ID</th>"+
"<th scope='col'>Username</th>"+
"<th scope='col'>House Number</th>"+
"<th scope='col'>Street</th>"+
"<th scope='col'>First Name</th>"+
"<th scope='col'>Last Name</th>"+
"<th scope='col'>No of Paid</th>"+
"<th scope='col'>Password</th>"+
"<th scope='col'>Phone</th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
result += "<td><button type='button' class='btn btn-danger btn-xs deleteBtn' onclick='deleteData(this);'>Delete</button></td>";
result += "<td><button type='button' class='btn btn-warning btn-xs editBtn' onclick='editData(this);'>Edit</button></td>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('dataTable');
div.innerHTML = result;
document.getElementById("message").innerHTML = "";
}else{
var div = document.getElementById('dataTable');
div.innerHTML = "Data not found!";
}
}
//DELETE DATA
function deleteData(el) {
var result = confirm("Want to delete?");
if (result) {
var username = el.parentNode.parentNode.cells[2].innerHTML;
google.script.run.withSuccessHandler(createTable).deleteData(username);
}
}
//EDIT DATA
function editData(el){
var username = el.parentNode.parentNode.cells[2].innerHTML; //https://stackoverflow.com/a/32377357/2391195
google.script.run.withSuccessHandler(populateForm).getRecordById(username);
}
//POPULATE FORM
function populateForm(records){
document.getElementById('username').value = records[0][0];
document.getElementById('housenumber').value = records[0][1];
document.getElementById('street').value = records[0][2];
document.getElementById('firstname').value = records[0][3];
document.getElementById('lastname').value = records[0][4];
document.getElementById('noOfPaid').value = records[0][5];
document.getElementById('password').value = records[0][6];
document.getElementById('phone').value = records[0][7];
document.getElementById("message").innerHTML = "<div class='alert alert-warning' role='alert'>Update Record [ID: "+records[0][0]+"]</div>";
}
//RETRIVE DATA FROM GOOGLE SHEET FOR STREET DROPDOWN
function createStreetDropdown() {
//SUBMIT YOUR DATA RANGE FOR DROPDOWN AS THE PARAMETER
google.script.run.withSuccessHandler(streetDropDown).getDropdownList("Configuration!A2:A11");
}
//POPULATE STREET DROPDOWNS
function streetDropDown(values) { //Ref: https://stackoverflow.com/a/53771955/2391195
var list = document.getElementById('street');
for (var i = 0; i < values.length; i++) {
var option = document.createElement("option");
option.value = values[i];
option.text = values[i];
list.appendChild(option);
}
}
//SEARCH DATA
function handleSearchForm(formObject) {
google.script.run.withSuccessHandler(createTable).searchData(formObject);
document.getElementById("search-form").reset();
}
</script>
AdminForm.html
<form id="adminForm" class="p-2 border border-light rounded bg-light" onsubmit="handleAdminFormSubmit(this)">
<p class="h4 mb-4 text-center">Admin Form</p>
<div id="admin_message"></div>
<input type="text" id="admin_message" name="admin_message" value="" style="display: none">
<div class="form-group">
<label for="admin_uname" >Username</label>
<input type="text" class="form-control" id="admin_uname" name="admin_uname" placeholder="Username" required>
</div>
<div class="form-group">
<label for="admin_pw" >Password</label>
<input type="password" class="form-control" id="admin_pw" name="admin_pw" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<input class="btn btn-secondary" type="reset" value="Reset">
</form>
This is my html and my JavaScript is below
in my html this is what i did please help me solve this problem i have been struggling for a couple of days not and i really don't know what i am doing wrong
this is my html and my JavaScript is below
let artistV = [];
function myPage() {
// body...
let htmlSelect = document.getElementById("artistList");
htmlSelect.style.visibility = "hidden";
if (sessionStorage.getItem("hasCodeRunBefore") === null) {
let arrayArt = [];
sessionStorage.setItem("artists", JSON.stringify(artistV));
sessionStorage.setItem("hasCodeRunBefore", true);
} else {
artistV = JSON.parse(sessionStorage.getItem("artists"));
let i = 0;
artistV.forEach(function(art) {
let listItems = document.createElements("li");
listItems.innerHTML = art.name.artist;
listItems.value = i;
i = i + 1;
htmlSelect.appendChild(listItems);
});
if (i > 0) {
htmlSelect.style.visibility = "visible";
}
}
}
function Artist(name, title, genre, album) {
// body...
this.name = name;
this.title = title;
this.genre = genre;
this.album = album;
}
function submit() {
// body...
artistV = JSON.parse(sessionStorage.getItem("artists"));
let newArtist = new Artist(
document.getElementById("name").value,
document.getElementById("title").value,
document.getElementById("genre").value,
document.getElementById("album").value
);
artistV.push(newArtist);
sessionStorage.setItem("artists", JSON.stringify(artistV));
}
function userInput(artistInfo) {
// body...
artistV[artistInfo].bio = function() {
document.getElementById("artistList").innerHTML = "<li value=''>"
this.name + 'Title is' + this.title + 'Genre is' + this.genre + 'Album is'
this.album + "</li>";
};
artistV[artistInfo].bio();
}
<!DOCTYPE html>
<html>
<head>
<title>Music</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script type="text/javascript" src="music.js"></script>
</head>
<body onload="myPage()">
<h1>Artist information</h1>
<br>
<form>
<label for="artistName">Artist name</label><input type="text" id="name" required>
<label>Title</label><input type="text" id="title" required>
<label>Genre</label><input type="text" id="genre" required>
<label>Album</label><input type="text" id="album" required>
<button id="btn" onclick="submit()">Submit</button>
</form>
<ul id="artistList" onchange="userInput(this.value)">
<li value=""></li>
</ul>
</body>
</html>
this is my JavaScript and i am not quite sure why it is not working to save what the user inputs on
[help], [help/on-topic]
Try renaming submit() function in your script to something else(say submitData).
Submit() method is inbuilt method which is used to submit the form to server.
Good morning, I tried to push a temporaly value to a JSON file with the comand "MyJSON.name.push" but it tells me: "Undefined its not an object". I tried some forms and with javascript arrays worked but I need to do it on external JSON file. The error only appears if I click some button. Someone can help me?
Thanks you.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) MyJSON.push('{name:"url",url:"url1"}')
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.name.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.urls.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.SSL= SSL;
}
JSON FILE(json.json):
var MyJSON = [{
name:"Google",
url: 'google.es',
},
{
name:"Yahoo",
url: 'yahoo.com',
}
]
Change your this.Add() function like this:
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.push({"name":url,"url":url1})
el.value = '';
this.FetchAll();
}
}
I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))