html sidebar data in not accessible - javascript

I have a google sheet, I opened script editor and opened there two files, a script file and an html file. Here is what I have in my script file:
//to load html sidebar
function loadHome() {
const htmlSidebar = HtmlService.createTemplateFromFile("home");
const htmlOutput = htmlSidebar.evaluate();
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
//to create a custom menu
function createMenu(){
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("AC Paz");
menu.addItem("Side Registration", "loadHome");
menu.addItem("Order Framing", "loadFraming");
menu.addToUi();
}
//to make sure custom menu is loaded on open
function onOpen(){
createMenu();
}
//to access data passed on html input fields
function userClicked(userInfo){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Site Information");
ws.appendRow([userInfo.firstName, userInfo.lastName, new Date()])
}
Here is what I have in my html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div >
<input id="fn" type="text" >
<label for="fn">First Name</label>
</div>
<div >
<input id="ln" type="text">
<label for="ln">Last Name</label>
</div>
<button id="btn">Add</button>
<script>
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.firstName = document.getElementById("fn").value;
userInfo.lastName = document.getElementById("ln").value;
google.script.run.userClicked(userInfo);
document.getElementById("fn").value = "";
document.getElementById("ln").value = "";
}
</script>
Here is my problem: when I type something in input fields and click the button, nothing is passed onto the spreadsheet, but, the entry gets cleared in the input fields.

Try this:
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div >
<input id="fn" type="text" >
<label for="fn">First Name</label>
</div>
<div >
<input id="ln" type="text">
<label for="ln">Last Name</label>
</div>
<button id="btn">Add</button>
<script>
window.onload=function(){
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.firstName = document.getElementById("fn").value;
userInfo.lastName = document.getElementById("ln").value;
google.script.run
.withSuccessHandler(function(){
document.getElementById("fn").value = "";
document.getElementById("ln").value = "";
})
.userClicked(userInfo);
}
}
</script>
</body>
</html>
GS:
function userClicked(userInfo){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Sheet1");
ws.appendRow([userInfo.firstName, userInfo.lastName, new Date()])
}
function showMySideBar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('ah1'))
}

Related

Google Apps Scripts - My button will not call the javascript function

This is the html code user input form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="marginauto" align="middle">
<style>
.marginauto {
margin: 10px auto 20px;
display: block;
}
</style>
<h1>
<img class="marginauto" align="middle" src="https://drive.google.com/uc?export=view&id=********" alt="*****">
Fabrication Time Record
</h1 >
<h2 class="marginauto" align="middle">
Information
</h2>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
<label for="jnum">Job number:</label><br>
<input type="text" id="jnum" name="jnum"><br>
<h2>
Operation
</h2>
<input type="radio" id="cut" name="operation" value="cut">
<label for="cut">Cut</label><br>
<input type="radio" id="drill" name="operation" value="drill">
<label for="drill">Drill</label><br>
<input type="radio" id="fitup" name="operation" value="fitUp">
<label for="fitup">Fit Up</label><br>
<input type="radio" id="weld" name="operation" value="weld">
<label for="weld">Weld</label><br>
<h2>
Comments
</h2>
<input type="text" id="comment"><br>
<br>
<button id="clockin">Clock in</button>
</div>
<script type="text/javascript">
document.getElementById("clockin").addEventListener("click",addLine);
function addLine(){
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var operation = document.getElementByName("operation");
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
}
google.script.run.addEntry(entry);
firstName.value = "";
lastName.value = "";
}
</script>
</body>
</html>
This is the script that takes user inputs from the html and (ideally) transfers them to a google spreadsheet:
function doGet(e){
Logger.log(e);
var html = HtmlService.createHtmlOutputFromFile("userForm");
html.setTitle("Record Time")
return(html)
}
function addEntry(entry){
Logger.log("Someone clicked the button");
var ssid = "1E81*****************QBmW1o4Q";
var ss = SpreadsheetApp.openById(ssid);
SpreadsheetApp.setActiveSpreadsheet(ss);
var database = ss.getSheetByName("Database");
SpreadsheetApp.setActiveSheet(database);
database.appendRow = ([entry]);
}
When I click the button, nothing happens. I am sure that I am calling the correct spreadsheet because I can read and write from the doGet() function, but there seems to be a problem with the addLine() function that I cannot find.
Any help is greatly appreciated, I am very new to web app development.
What I want is for the button to transfer the data from some text input fields to a google spreadsheet. I used multiple different button syntaxes but cannot nothing happens.
You are passing an object to addEntry you should pass an array.
Change
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
};
To
var entry = [
firstName.value,
lastName.value,
operation.value
];
Also you have a typo in your client script. Change
var operation = document.getElementByName("operation");
To
var operation = document.getElementsByName("operation");
However getElementsByName returns a node list so to find the checked radio button you need to add this to your client script.
let operations = document.getElementsByName("operation");
let operation = null;
for( let i=0; i<operations.length; i++ ) {
if( operations[i].checked ) {
operation = operations[i];
break;
}
}

Apps Script WebApp - Update text box field from data from a google sheet

I'm busy with an Apps Script Web App and would like to populate input boxes within the web app with data from a google sheet.
I'm trying to retrieve data when a button is clicked and populate fields within the webapp with the data that is retrieved from the sheet. I just can't seem to get the text box fields to be updated after retrieving the data from google sheets.
Any help would be greatly appreciated.
The code I have so far is:
Code.gs file
function doGet() {
var htmlOutput = HtmlService.createTemplateFromFile("page");
return htmlOutput.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
var idx;
var nextLead;
var totalLeads;
var remainingLeads;
function assignLead() {
var ss = SpreadsheetApp.openById("sheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
var data = range.getValues();
//console.log(data);
var status = data.map(function (row) {
return row[11];
});
//console.log(status);
idx = status.indexOf("unassigned");
//console.log(idx)
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
function updateStatusAssigned(row) {
var ss = SpreadsheetApp.openById("SheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
ws.getRange(idx + 1, 12).setValue("assigned")
}
page html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<?!= include("page-css") ?>
</head>
<body>
<div>
<!-- Header -->
<div class="header">
<h1>Header</h1>
</div>
<!-- Agent Info -->
<div class="row">
<div>
<p><label for="agnet">Agent Name:</label><input id="agent" type="text" ></input>
<label for="loginTime">Login Time:</label><input id="loginTime" type="text"></input></p>
<p><label for="campaign">Current Campaign:</label><input type="text" id="campaign"></input></p>
<button id="btn-getLead" style= float: right>Get Lead</button>
</div>
<!-- <div>
<button id="btn" style=”float: right”>Get Lead</button>
</div> -->
</div>
<!-- Lead Details Banner -->
<div class="row">
<div class="container">
<h3>Lead Details</h3>
</div>
<!-- Customer Information -->
<div class="flex-container">
<div>
<p>
<h5>Customer Information</h5>
</P>
<label>Name:</label><input type="text" id="name"></input>
<label>Surname:</label><input type="text" id="surname"></input>
<label>ID Number:</label><input type="text" id="id"></input>
<p><label>Address:</label><input type="text" id="add"></input><label>Postal Code:</label><input type="text" id="code"></input></p>
<p><label>Suburb:</label><input type="text" id="sub"></input></P>
<p><label>Postal Address:</label><input type="text" id="p-add"></input></p>
<p><label>Tel Number:</label><input type="tel" id="tel"></input>
<label>Mobile Number:</label><input type="tel" id="cell"></input>
<label>Alternate Number:</label><input type="tel" id="alt"></input></p>
<p>
<label>Disposition</label>
<select id="dispo">
<option> </option>
<option>Wrong Number</option>
<option>No Answer</option>
<option>Win</option>
</select>
</p>
<p>
<button id="submit">Submit</button>
</p>
</div>
<!-- Call Notes -->
<div>
<p>
<h5>Call Notes</h5>
</p>
<textarea rows="15" cols="50" id="notes"></textarea>
</div>
</div>
<?!= include("page-js") ?>
</body>
</html>
page-js file
<script>
document.getElementById("btn-getLead").addEventListener("click",getLeadData);
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
</script>
Modification points:
Unfortunately, the variables declared as the global at Google Apps Script side cannot be used for Javascript side. So nextLead of document.getElementById("name") = nextLead[0]; cannot be used.
I thought that this is due to the reason of your issue.
In this case, withSuccessHandler can be used.
And, I think that document.getElementById("name") = nextLead[0]; occurs an error. In this case, please modify to document.getElementById("name").value = nextLead[0];.
When above points are reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
Please modify assignLead() as follows.
From:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
To:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
return nextLead; // Added
}
Javascript side:
From:
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
To:
function getLeadData(){
google.script.run.withSuccessHandler(nextLead => {
document.getElementById("name").value = nextLead[0];
}).assignLead();
}
Note:
In this modified script, it supposes that your function of assignLead() works fine and nextLead is the correct value you want. Please be careful this.
Reference:
withSuccessHandler(function)

Google Sheets + Apps Script + Webapps: Pull and edit an existing row data and update row

Hi I'm trying to pull the data from a google sheet from the row that matches the selected ID number to edit the data then click on the update button so the matching row gets updated in google sheet here's a link to my google sheet. https://docs.google.com/spreadsheets/d/1eaEfRtjMz7kyQfyXZHLuBhSz91SiUJzq1J2QJexJxy4/edit?ts=5fc42833#gid=0
here's my gs code
function doGet(request) {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function getCustDetail(search) {
var ss = SpreadsheetApp.getActive()
var ws = ss.getSheetByName("Data");
var idvCustData = ws.getRange(2,1,ws.getLastRow(),8).getValues();
var custIdList = idvCustData.map(function(r){ return r[0]; });
var custDateList = idvCustData.map(function(r){ return r[2]; });
var custclientList = idvCustData.map(function(r){ return r[3]; });
var custlocationList = idvCustData.map(function(r){ return r[4]; });
var custother1List = idvCustData.map(function(r){ return r[5]; });
var custother2List = idvCustData.map(function(r){ return r[6]; });
var searchPostion = custIdList.indexOf(search);
var custDetail = {};
custDetail.custId = custIdList[searchPostion];
custDetail.custDate = custDateList[searchPostion];
custDetail.custclient = custclientList[searchPostion];
custDetail.custlocation = custlocationList[searchPostion];
custDetail.custother1 = custother1List[searchPostion];
custDetail.custother2 = custother2List[searchPostion];
Logger.log(searchPostion);
Logger.log(custDetail);
Logger.log(search);
if (searchPostion > -1){
return custDetail;
} else {
return '-';
}
}
here's my JS code
<script>
// 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', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
//Retrieve Customer
function getCustomer() {
var searchId = document.getElementById("Id").value;
if (searchId != ""){
google.script.run.withSuccessHandler(custDetail).getCustDetail(searchId);
}
}
//Success Handler
function custDetail(){
document.getElementById("Id").innerHTML = cust.Id;
document.getElementById("Date").innerHTML = cust.Date;
document.getElementById("client").innerHTML = cust.client;
document.getElementById("location").innerHTML = cust.location;
document.getElementById("other1").innerHTML = cust.other1;
document.getElementById("other2").innerHTML = cust.other2;
M.updateTextFields();
}
</script>
Here's my HTML code
<!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>
<?!= include('JavaScript'); ?>
<?!= include('CSS'); ?>
<!-- Select2 CDN -->
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!-- CSS only -->
<link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity= "sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous">
<!-- JS, Popper.js, jquery and jQuery autocomplete -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity= "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous">
</script>
<script src= "https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity= "sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous">
</script>
<script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity= "sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous">
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p class="h4 mb-4 text-center">Ticket Form</p>
<div class="form-row">
<div class="form-group col-md-2">
<label for="Id">ID</label>
<input type="text" class="form-control" id="Id" name ="Id">
</div>
<div class="form-group col-md-2">
<label for="Date">Ticket Date</label>
<input type="date" class="form-control" id="Date" name ="Date">
</div>
<div class="form-group col-md-4">
<label for="client">Client</label>
<input type="text" class="form-control" id="client" name="client" >
</div>
<div class="form-group col-md-4">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" name="location" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<label for="other1">Other1</label>
<input type="text" class="form-control" id="other1" name ="other1">
</div>
<div class="form-group col-md-4">
<label for="other2">Other2</label>
<input type="text" class="form-control" id="other2" name="other2" >
</div>
</div>
<hr>
<br>
<button type="submit" class="btn btn-primary btn-block col-md-4 ">Update</button>
</form>
<br>
<div id="output"></div>
</div>
</div>
</div>
</body>
Modification points:
At Google Apps Script side:
When I saw the scripts in your shared Spreadsheet, it seems that the function getCustDetail doesn't return the values. But, your script in your question returns custDetail.
At getCustDetail, you have already set the value of search. So in this case, the value is always used. Please be careful this.
When the value is put to the input with type="date", the value is required to be yyyy-MM-dd.
Even when custDetail is returned, custDetail() at Javascript side doesn't use the argument.
Even when custDetail uses the argument from Google Apps Script side, the keys returned from Google Apps Script are different from them at Javascript side.
At Javascript side:
In your shared Spreadsheet, var data = google.script.run.getCustDetail(); is used. But in the current stage, google.script.run returns no values. Please be careful this.
When you want to set the value to the text input, please use value instead of innerHTML.
When above points are reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
Please modify getCustDetail as follows.
function getCustDetail(search) {
search = Number(search);
var ss = SpreadsheetApp.getActive();
var ws = ss.getSheetByName("Data");
var idvCustData = ws.getRange(2,1,ws.getLastRow(),8).getValues();
var custIdList = idvCustData.map(function(r){ return r[0]; });
var custDateList = idvCustData.map(function(r){ return r[2]; });
var custclientList = idvCustData.map(function(r){ return r[3]; });
var custlocationList = idvCustData.map(function(r){ return r[4]; });
var custother1List = idvCustData.map(function(r){ return r[5]; });
var custother2List = idvCustData.map(function(r){ return r[6]; });
var searchPostion = custIdList.indexOf(search);
var custDetail = {};
custDetail.Id = custIdList[searchPostion];
custDetail.Date = custDateList[searchPostion] && Utilities.formatDate(custDateList[searchPostion], Session.getScriptTimeZone(), "yyyy-MM-dd");
custDetail.client = custclientList[searchPostion];
custDetail.location = custlocationList[searchPostion];
custDetail.other1 = custother1List[searchPostion];
custDetail.other2 = custother2List[searchPostion];
if (searchPostion > -1){
return custDetail;
} else {
return null;
}
}
In this case, it supposes that IDs of the column "A" in Spreadsheet are always the number. Please be careful this.
Javascript side:
Please modify custDetail as follows.
function custDetail(cust){
if (cust) {
document.getElementById("Id").value = cust.Id;
document.getElementById("Date").value = cust.Date;
document.getElementById("client").value = cust.client;
document.getElementById("location").value = cust.location;
document.getElementById("other1").value = cust.other1;
document.getElementById("other2").value = cust.other2;
M.updateTextFields();
}
}
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

Update from NATIVE sandbox to IFRAME; button not working

Since the NATIVE sandbox on google apps script is deprecated, I'm switching to IFRAME, which has caused some issues.
The basic outline of the app is that it should allow a user to fill in some information and upload a file (it also makes sure all required fields are completed). Upon submission (by clicking a button), the file should be uploaded to a folder in google drive and a spreadsheet should be updated with the user's information. When I'm in NATIVE, everything works fine. When I set it to IFRAME, nothing happens when I click the submit button.
This is a similar issue to here and here, but neither of them directly address my problem. I also tried following the Google Guide but it didn't help.
Here is my server.gs script:
function doGet(e) {
return template = HtmlService.createHtmlOutputFromFile('form.html').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFiles(form) {
try {
var dropbox = "Applications";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var CV = form.CV;
var foldername = form.myLastName + ", " + form.myFirstName;
var myFolder = folder.createFolder(foldername);
var file_CV = myFolder.createFile(CV);
var CV_url = file_CV.getUrl();
var sheet_return = addApplicant(form, CV_url);
return "Thank you for your submission."
} catch (error) {
return error.toString();
}
}
function addApplicant(form, CV_url) {
try {
var d = new Date()
var ss = SpreadsheetApp.openByUrl(***INSERT URL TO GOOGLE SHEETS PAGE***);
SpreadsheetApp.setActiveSpreadsheet(ss);
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var sheet = SpreadsheetApp.getActiveSheet();
if (form.visa != "Yes"){
form.visa = "No"
}
sheet.appendRow([d, form.myFirstName, form.myLastName, form.myEmail, form.visa, CV_url]);
} catch (error) {
return error.toString();
}
}
Here is my form.html script:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<!-- You can also include your own CSS styles -->
<link href='https://fonts.googleapis.com/css?family=Bitter' rel='stylesheet' type='text/css'>
<style type="text/css">
.warning {border: 1px solid red !important; background: #fdecb2 !important;}
.hideClass {display:none;}
</style>
<div class="form-style-10">
<title> Application </title>
<form id="myForm" name="myForm">
<fieldset class="fields">
<div class="section"> Personal Information </div>
<div class="inner-wrap">
<label for="myFirstName"> First Name* </label>
<input type="text" id="myFirstName" name="myFirstName" placeholder="" required />
<label for="myLastName"> Last Name* </label>
<input type="text" name="myLastName" placeholder="" required />
<label for="myEmail"> Email* </label>
<input type="email" name="myEmail" placeholder="" required />
<span class="visa-checkbox">
Check if you will require visa assistance. <input type="checkbox" name="visa" value="Yes" />
</span>
</div>
</fieldset>
<fieldset class="fields">
<div class="section"> Documents (pdf format is preferred) </div>
<div class="inner-wrap">
<label for="CV"> CV* </label>
<input type="file" name="CV" required />
</div>
</fieldset>
<p> </p>
<p id="incompleteWarning" class="hideClass"> Please check for incomplete fields and re-submit. </p>
<p id="bePatient" class="hideClass"> Please be patient while the files are being uploaded. Do not close or refresh the form. </p>
<input id="submitbutton" type="button" value="Submit Application" />
</form>
<div id="output" class="hideClass">
<span id="ThankYou" >Thank you for taking the time to complete the application.
</span>
</div>
</div>
<script type="text/javscript">
document.getElementById('submitbutton').addEventListener("click", validatefunction);
function validatefunction() {
document.getElementById('submitbutton').val = 'Submitting...';
//check for required fields
var j = 0;
var form = document.getElementById('myForm');
var elem = form.elements;
for (var i = 0; i < elem.length; i++){
elem[i].className = "";
if (elem[i].value === "" && elem[i].hasAttribute('required')){
elem[i].className = "warning";
j++;
}
}
if (j === 0) {
var btn = document.getElementById('submitbutton');
btn.disabled = true;
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
document.getElementById('submitbutton').val = 'Submit Application';
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
};
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').style.display = 'inline';
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
</body>
</html>
Change:
<script type="text/javscript">
To:
<script language="javascript">
I don't know why it doesn't like type="text/javscript"

Categories

Resources