HTML Button not Linked to Javascript - javascript

Working on an HTML integration with GAS, the following code is not doing anything but generating a white, seemingly empty form upon clicking "Add":
//GLOBALS
let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var lastCol = ss.getLastColumn();
var ui = SpreadsheetApp.getUi();
var arrEndRow;
var icaoFindMatch = 0;
//Upon opening spreadsheet, menu items are added and a test is made to determine
//if there are any entries and if not, it will load an entry form
function onOpen(e) {
//creates custom menu
ui.createMenu('Catering Menu')
.addItem('Search Locations', 'menuItem1')
.addItem('Add Catering Info', 'menuItem2')
.addToUi();
//test if there is at least one entry
if (lastRow == 1){
loadForm(); //run entry form
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Use the 'Catering Menu' dropdown on the toolbar to search, add or modify existing catering info.","User Notice",-1);
}
}
function testMe(){
ui.alert("in TestMe");
}
//takes info entered on the uForm.html and enters it under the appropriate ICAO location
function addNewRow(rowData){
ui.alert("in addNewRow");
/*
var icaoResult = ui.prompt("Please input your ICAO");
var resultText = icaoResult.getResponseText();
*/
let icaoRangeInit = ss.getRange(2,1,lastRow-1,1).getValues();
let icaoArr = icaoRangeInit.filter((string) => string != "");
let icaoArrLast = icaoArr[icaoArr.length-1];
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>Catering Entry Form</title>
</head>
<body>
<form>
<div class="form-floating mb-4">
<input type="text" class="form-control" id="floatingLocation" placeholder="ICAO Location">
<label for="floatingLocation">ICAO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingName" placeholder="Name">
<label for="floatingName">Name</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDistance" placeholder="Distance (mi)">
<label for="floatingDistance">Distance (mi)</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDriveTime" placeholder="Drive Time (min)">
<label for="floatingDriveTime">Drive Time (min)</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingPhoneNum" placeholder="Phone #">
<label for="floatingPhoneNum">Phone Number</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingSite" placeholder="Website">
<label for="floatingSite">Website</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingDelivery" placeholder="Delivery?">
<label for="floatingDelivery">Delivery (Yes/No)</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Notes" id="floatingTextarea"></textarea>
<label for="floatingTextarea">Notes</label>
</div>
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
</form>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- script to take the values inputted in fields above and transfer to spreadsheet -->
<script>
function afterButtonClicked() {
google.script.run.testMe();
var icao = document.getElementById("floatingLocation");
var name = document.getElementById("floatingName");
var dist = document.getElementById("floatingDistance");
var driveTime = document.getElementById("floatingDriveTime");
var phoneNum = document.getElementById("floatingPhoneNum");
var site = document.getElementById("floatingSite");
var delivery = document.getElementById("floatingDelivery");
var notes = document.getElementById("floatingTextarea");
var rowData = {icao: icao.value, name: name.value, dist: dist.value, driveTime: driveTime.value, phoneNum: phoneNum.value, site: site.value, delivery: delivery.value, notes: notes.value};
//google.script.run.testMe();
}
document.getElementById("AddtoWS").addEventListener("click", afterButtonClicked); //tells the "Add" button what to do
</script>
</body>
</html>
That's the entirety of the HTML which does everything from loading the sidebar and input fields, all the way to the button but it's not properly calling my Javascript in the Code.js
Also, I only pasted the top snippet of my Code.js because it's clear I'm not evening getting to where I can get the testMe() function called to check that the handshake between html and js is even working.
I've spent more hours trying to figure this out than I care to admit, any help would be greatly appreciated!
Colin

You have not called on onclick. You can call the function as shown below.
<div>
<button class="btn btn-primary" onclick="afterButtonClicked()" id="AddtoWS">Add</button>
</div>

You need to add an attribute to the button called onclick, which tells the webpage what to do if that button is clicked, for ex.
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
should be changed to
<div>
<button class="btn btn-primary" id="AddtoWS" onclick="functionYouWantToRun()">Add</button>
</div>
if JS file is connected to it even with the src attribute, it will work the same, just add the code to run,
or you can add an eventListener. Ex:
document.getElementById(AddtoWs).addEventListener('click',function(){
//Add the JS code you want to run
});
, it will basically run the code inside the function(){}, once someone clicks the button.
Edit: I just double-checked your code and you added the eventListener, but there is a problem, you need to add the function before you use the addEventLsitener.
Edit No.2: Try adding the function in the eventListener, I made a mistake in the first edit.
Edit No,3: Try this code, This should work:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<!-- Refering the JS code you had first put-->
<script src="anyname.js"></script>
<!---->
<title>Catering Entry Form</title>
</head>
<body>
<form>
<div class="form-floating mb-4">
<input type="text" class="form-control" id="floatingLocation" placeholder="ICAO Location">
<label for="floatingLocation">ICAO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingName" placeholder="Name">
<label for="floatingName">Name</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDistance" placeholder="Distance (mi)">
<label for="floatingDistance">Distance (mi)</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDriveTime" placeholder="Drive Time (min)">
<label for="floatingDriveTime">Drive Time (min)</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingPhoneNum" placeholder="Phone #">
<label for="floatingPhoneNum">Phone Number</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingSite" placeholder="Website">
<label for="floatingSite">Website</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingDelivery" placeholder="Delivery?">
<label for="floatingDelivery">Delivery (Yes/No)</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Notes" id="floatingTextarea"></textarea>
<label for="floatingTextarea">Notes</label>
</div>
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
</form>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- script to take the values inputted in fields above and transfer to spreadsheet -->
<script>
/*function afterButtonClicked() {
}*/
document.getElementById("AddtoWS").addEventListener('click', function(){
google.script.run.testMe();
var icao = document.getElementById("floatingLocation");
var name = document.getElementById("floatingName");
var dist = document.getElementById("floatingDistance");
var driveTime = document.getElementById("floatingDriveTime");
var phoneNum = document.getElementById("floatingPhoneNum");
var site = document.getElementById("floatingSite");
var delivery = document.getElementById("floatingDelivery");
var notes = document.getElementById("floatingTextarea");
var rowData = {icao: icao.value, name: name.value, dist: dist.value, driveTime: driveTime.value, phoneNum: phoneNum.value, site: site.value, delivery: delivery.value, notes: notes.value};
//google.script.run.testMe();
}); //tells the "Add" button what to do
</script>
</body>
</html>
,anyname.js:
//GLOBALS
let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var lastCol = ss.getLastColumn();
var ui = SpreadsheetApp.getUi();
var arrEndRow;
var icaoFindMatch = 0;
//Upon opening spreadsheet, menu items are added and a test is made to determine
//if there are any entries and if not, it will load an entry form
function onOpen(e) {
//creates custom menu
ui.createMenu('Catering Menu')
.addItem('Search Locations', 'menuItem1')
.addItem('Add Catering Info', 'menuItem2')
.addToUi();
//test if there is at least one entry
if (lastRow == 1){
loadForm(); //run entry form
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Use the 'Catering Menu' dropdown on the toolbar to search, add or modify existing catering info.","User Notice",-1);
}
}
function testMe(){
ui.alert("in TestMe");
}
//takes info entered on the uForm.html and enters it under the appropriate ICAO location
function addNewRow(rowData){
ui.alert("in addNewRow");
/*
var icaoResult = ui.prompt("Please input your ICAO");
var resultText = icaoResult.getResponseText();
*/
let icaoRangeInit = ss.getRange(2,1,lastRow-1,1).getValues();
let icaoArr = icaoRangeInit.filter((string) => string != "");
let icaoArrLast = icaoArr[icaoArr.length-1];

Related

My tip calculator code is not working. Where is the error in the code?

The two problems that i think with the code are that its not saving the input values therefore the the code is not displaying any result and secondly from the dropdown list only first option gets selected everytime. Kindly let me know the errors in the code. I am new to coding.
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Tip Calculator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<form>
<div class="mb-3">
<label class="total form-label">Total Bill</label>
<input type="number" class="form-control" id="bill" >
<div id="emailHelp" class="form-text">Please Enter your bill in numbers only.</div>
</div>
<div class="mb-3">
<label class="form-label">Number of People</label>
<input type="number" class="form-control" id="people">
</div>
<!-- <div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div> -->
<select class="form-select" id="myValues">
<option value="30%">Select the service quality</option>
<option value="30%">30% - Outstanding</option>
<option value="20%">20% - Good</option>
<option value="15%">15% - it was okay</option>
<option value="5%">5% - Terrible</option>
</select>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
<div id="totalTip">
<sup>$</sup><span class="form-label" id="tip">0.00</span>
<small id="each">each</small>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="tip.js" charset="utf-8"></script>
</html>
This is the javascript code
var a = $("#bill").val();
var b = $("#people").val();
var c = $("#myValues").find('option:selected').val();
$(".btn").click(function () {
$("#tip").html(calculateTip(a, b, c));
});
function calculateTip (total, people, select) {
var d = total/people;
var e = d*(select/100);
return e;
}
// calculateTip(a, b, c)
A couple of issues stand out.
you define a, b, and c at the beginning of the script, before the user has interacted with the form. We should define then inside the click handler, this way they will be evaluated and set when the button is clicked.
You may want to add a e.preventDefault(); inside the click handler to stop the default submit behavior (ie stop it from trying to submit the form)
You don't need to find the selected option for #myValues, you can access the currently selected value directly via $("#myValues").val()
You'll want to remove the % from the option values so you can do math with the value (You'll get NaN with the % in place which makes the value a string.
You'll likely want to add a .toFixed(2) to the tip result to force it to round to and truncate at 2 decimal places to avoid long repeating decimals
$(".btn").click(function(e) {
e.preventDefault();
let a = $("#bill").val();
let b = $("#people").val();
let c = $("#myValues").val();
let tip = calculateTip(a, b, c);
$("#tip").html(tip);
});
function calculateTip(total, people, select) {
var d = total / people;
var e = d * (select / 100);
return e.toFixed(2);
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Tip Calculator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<form>
<div class="mb-3">
<label class="total form-label">Total Bill</label>
<input type="number" class="form-control" id="bill">
<div id="emailHelp" class="form-text">Please Enter your bill in numbers only.</div>
</div>
<div class="mb-3">
<label class="form-label">Number of People</label>
<input type="number" class="form-control" id="people">
</div>
<!-- <div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div> -->
<select class="form-select" id="myValues">
<option value="30">Select the service quality</option>
<option value="30">30% - Outstanding</option>
<option value="20">20% - Good</option>
<option value="15">15% - it was okay</option>
<option value="5">5% - Terrible</option>
</select>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
<div id="totalTip">
<sup>$</sup><span class="form-label" id="tip">0.00</span>
<small id="each">each</small>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</html>

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.

To check if the inputs inside the form are are required or not for inputs with some directive

Hello I want to find that if all the required fields are filled or not in the form using jquery only
I have tried this
$('#form').find('input,select, textarea').each(function(){
if(!$(this).prop('required')){
console.log("NR");
} else {
console.log("IR");
}
});
//but from this I got to know about only fields with input type or select and textarea, I am not able to know about the fields with uses some third party here the uib-rating
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form">
<div class="row" id="D_1">
First name:<br>
<input type="text" name="firstname" value="ab" ng-model="fname" required>
<br>
Last name:<br>
<input type="text" name="lastname" value = "" required = "fname === 'abc'">
</div>
<div class="row" id="D_2">
notes:<br>
<input type="text" name="notes" >
</div>
<div class="row" id="D_3">
<textarea name="tarea"></textarea>
<span uib-rating titles=[] ng-model="" max="5" name="rating"
on-leave="overStar = null" ng-required="fname === 'abc'"></span>
</div>
</div>
but from this I got to know about only fields with input type or select and textarea, I am not able to know about the fields with uses some third party or some build in directive (here the uib-rating)
Please help me to check for required for these kinds of fields also
//I have already tried this:
$('.form-field').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
but not working for third party
If you just want to know if all of them are filled or not use:
function validateForm() {
var isValid = true;
$('#form').find('input:required,select:required, textarea:required').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
DEMO
function validateForm() {
var isValid = true;
$('#form').find('input:required,select:required, textarea:required').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
$(".validate").click(function() {
console.log(validateForm());
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form">
<div class="row" id="D_1">
First name:<br>
<input type="text" name="firstname" value="ab" ng-model="fname" required>
<br> Last name:<br>
<input type="text" name="lastname" value="" required="fname === 'abc'">
</div>
<div class="row" id="D_2">
notes:<br>
<input type="text" name="notes">
</div>
<div class="row" id="D_3">
<textarea name="tarea"></textarea>
<span uib-rating titles=[] ng-model="" max="5" name="rating" on-leave="overStar = null" ng-required="fname === 'abc'"></span>
</div>
</div>
<button class="validate">validate</button>

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>

Categories

Resources