英文:
include(page) function for script not loading DOM references
问题
以下是代码部分的翻译:
Using Google Apps Script HtmlService class to produce some output. This specific case is for a Google Sheets sidebar, but I'm also running into it when utilizing as a web app.
I'm running into an issue where if I put my script directly into the html file, the DOM references work fine. Once I put them into and <?!= include("page") ?> scriptlet, it throws an error;
> Uncaught TypeError: Cannot read properties of null (reading 'value')
Here is the html form and scriptlet:
!= include('LOGO') ?>
!= include("AddEmpJS") ?>
```
This is the AddEmpJS.html referenced by the include function;
<script>
function addRecord() {
let fname = document.getElementById("fName").value
let lname = document.getElementById("lName").value
let empId = document.getElementById("empId").value
let job = document.getElementById("job").value
let wage = document.getElementById("wage").value
let job2 = document.getElementById("jobtwo").value
let wage2 = document.getElementById("wagetwo").value
let job3 = document.getElementById("jobthree").value
let wage3 = document.getElementById("wagethree").value
let record = [
fname, lname, empId, job, wage, job2, wage2, job3, wage3
]
console.log(record)
google.script.run.addEmpRecord(record);
document.getElementById("add").reset()
}
function moreJobs() {
if(document.getElementById("job2").style.display == "none") {
document.getElementById("job2").style.display = "block"
document.getElementById("wage2").style.display = "block"
return "job 2 showing"
}
if(document.getElementById("job3").style.display == "none") {
document.getElementById("job3").style.display = "block"
document.getElementById("wage3").style.display = "block"
return "job 3 showing"
}
}
function lessJobs() {
if(document.getElementById("job3").style.display == "block") {
document.getElementById("job3").style.display = "none"
document.getElementById("wage3").style.display = "none"
return "removing job 3"
}
if(document.getElementById("job2").style.display == "block") {
document.getElementById("job2").style.display = "none"
document.getElementById("wage2").style.display = "none"
return "removing job 2"
}
}
function closeSide() {
google.script.host.close()
}
</script>
The include function on the server side,
function include(page) {
return HtmlService.createHtmlOutputFromFile(page).getContent();
}
The UI that calls the sidebar,
function addEmp() {
var page = HtmlService.createTemplateFromFile("AddEmp").evaluate();
page.setTitle("💼 Add Employee")
ui.showSidebar(page)
and the whole script,
const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EMPLOYEES");
const setup = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SETUP");
const summary = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SUMMARY");
const ui = SpreadsheetApp.getUi();
function onOpen(e) {
ui.createMenu("👔 Employees")
.addItem("💼 Add Employee", "addEmp")
.addItem("✨ Edit Employee", "editEmp")
.addItem("🔥 Del Employee", "delEmp")
.addToUi();
ui.createMenu("📋 Departments")
.addItem("➕ Add Department", "addDept")
.addItem("🔧 Edit Department", "editDept")
.addItem("➖ Del Department", "delDept")
.addToUi();
ui.createMenu("⌚ Schedule")
.addItem("📅 Add Week", "addSched")
.addItem("🔎 Update Summary Tab", "updateTabs")
.addToUi();
updateTabs();
}
function updateTabs() {
var tabList = SpreadsheetApp.getActiveSpreadsheet().getSheets().map((s) => s.getName())
.filter((s) => s != "SETUP" && s != "EMPLOYEES" && s != "TEMPLATE" && s != "SUMMARY")
Logger.log(tabList)
var rule = SpreadsheetApp.newDataValidation().requireValueInList(tabList)
var dropDown = summary.getRange("A1").setDataValidation(rule).activate();
}
function include(page) {
return HtmlService.createHtmlOutputFromFile(page).getContent();
}
//ADD EDIT & REMOVE EMPLOYEE HTML
function addEmp() {
var page = HtmlService.createTemplateFromFile("AddEmp").evaluate();
page.setTitle("💼 Add Employee")
ui.showSidebar(page)
}
function editEmp() {
var page = HtmlService.createHtmlOutputFromFile("EditEmp")
.setTitle("✨ Edit Employee");
ui.showSidebar(page)
}
function delEmp() {
var page = HtmlService.createHtmlOutputFromFile("DelEmp")
.setTitle("🔥 Delete Employee");
ui.showSidebar(page)
}
//checks for an id# and job code
// if id# already exist, err to checkId
// if job doesn't exist, eff to checkJob
function addEmpRecord(record) {
let array
<details>
<summary>英文:</summary>
Using Google Apps Script HtmlService class to produce some output. This specific case is for a Google Sheets sidebar, but I'm also running into it when utilizing as a web app.
I'm running into an issue where if I put my script directly into the html file, the DOM references work fine. Once I put them into and <?!= include("page") ?> scriptlet, it throws an error;
> Uncaught TypeError: Cannot read properties of null (reading 'value')
Here is the html form and scriptlet:
<body>
<?!= include('LOGO') ?>
<form id="add">
<div><input id=" fName" type="text" /> First Name</div>
<div><input id="lName" type="text" /> Last Name</div>
<div><input id="empId" type="text" /> ID#</div>
<div><input id="job" type="text" /> Job</div>
<div><input id="wage" type="text" /> Wage</div>
<div id="job2" type="text" style="display: none"><input id="jobtwo" type="text" /> Job 2</div>
<div id="wage2" type="text" style="display: none"><input id="wagetwo" type="text" /> Wage 2</div>
<div id="job3" type="text" style="display: none"><input id="jobthree" type="text" /> Job 3</div>
<div id="wage3" type="text" style="display: none"><input id="wagethree" type="text" /> Wage 3</div>
<div>
<button id="enter" type="button" onclick="addRecord()"> Enter</button>
<button id="more" type="button" onclick="moreJobs()"> + Job</button>
<button id="less" type="button" onclick="lessJobs()"> - Job</button>
<button id="close" type="button" onclick="closeSide()"> Close</button>
</div>
</form>
<?!= include("AddEmpJS") ?>
</body>
This is the AddEmpJS.html referenced by the include function;
<script>
function addRecord() {
let fname = document.getElementById("fName").value
let lname = document.getElementById("lName").value
let empId = document.getElementById("empId").value
let job = document.getElementById("job").value
let wage = document.getElementById("wage").value
let job2 = document.getElementById("jobtwo").value
let wage2 = document.getElementById("wagetwo").value
let job3 = document.getElementById("jobthree").value
let wage3 = document.getElementById("wagethree").value
let record = [
fname, lname, empId, job, wage, job2, wage2, job3, wage3
]
console.log(record)
google.script.run.addEmpRecord(record);
document.getElementById("add").reset()
}
function moreJobs() {
if(document.getElementById("job2").style.display == "none") {
document.getElementById("job2").style.display = "block"
document.getElementById("wage2").style.display = "block"
return "job 2 showing"
}
if(document.getElementById("job3").style.display == "none") {
document.getElementById("job3").style.display = "block"
document.getElementById("wage3").style.display = "block"
return "job 3 showing"
}
}
function lessJobs() {
if(document.getElementById("job3").style.display == "block") {
document.getElementById("job3").style.display = "none"
document.getElementById("wage3").style.display = "none"
return "removing job 3"
}
if(document.getElementById("job2").style.display == "block") {
document.getElementById("job2").style.display = "none"
document.getElementById("wage2").style.display = "none"
return "removing job 2"
}
}
function closeSide() {
google.script.host.close()
}
</script>
The include function on the server side,
`function include(page) {
return HtmlService.createHtmlOutputFromFile(page).getContent();
}`
The UI that calls the sidebar,
function addEmp() {
var page = HtmlService.createTemplateFromFile("AddEmp").evaluate();
page.setTitle("💼 Add Employee")
ui.showSidebar(page)
and the whole script,
const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EMPLOYEES");
const setup = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SETUP");
const summary = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SUMMARY");
const ui = SpreadsheetApp.getUi();
function onOpen(e) {
ui.createMenu("👔 Employees")
.addItem("💼 Add Employee", "addEmp")
.addItem("✨ Edit Employee", "editEmp")
.addItem("🔥 Del Employee", "delEmp")
.addToUi();
ui.createMenu("📋 Departments")
.addItem("➕ Add Department", "addDept")
.addItem("🔧 Edit Department", "editDept")
.addItem("➖ Del Department", "delDept")
.addToUi();
ui.createMenu("⌚ Schedule")
.addItem("📅 Add Week", "addSched")
.addItem("🔎 Update Summary Tab", "updateTabs")
.addToUi();
updateTabs();
}
function updateTabs() {
var tabList = SpreadsheetApp.getActiveSpreadsheet().getSheets().map((s) => s.getName())
.filter((s) => s != "SETUP" && s != "EMPLOYEES" && s != "TEMPLATE" && s != "SUMMARY")
Logger.log(tabList)
var rule = SpreadsheetApp.newDataValidation().requireValueInList(tabList)
var dropDown = summary.getRange("A1").setDataValidation(rule).activate();
}
function include(page) {
return HtmlService.createHtmlOutputFromFile(page).getContent();
}
//ADD EDIT & REMOVE EMPLOYEE HTML
function addEmp() {
var page = HtmlService.createTemplateFromFile("AddEmp").evaluate();
page.setTitle("💼 Add Employee")
ui.showSidebar(page)
}
function editEmp() {
var page = HtmlService.createHtmlOutputFromFile("EditEmp")
.setTitle("✨ Edit Employee");
ui.showSidebar(page)
}
function delEmp() {
var page = HtmlService.createHtmlOutputFromFile("DelEmp")
.setTitle("🔥 Delete Employee");
ui.showSidebar(page)
}
//checks for an id# and job code
// if id# already exist, err to checkId
// if job doesn't exist, eff to checkJob
function addEmpRecord(record) {
let array_target = ws.getRange("C2");
let array_formula = array_target.getFormula();
array_target.clear();
if (!checkId(record[2]) && !checkJob(record[3])) {
ws.getRange(ws.getLastRow() + 1, 1, 1, 10).setValues([[
record[0], record[1], , record[2].toString(), record[3].toUpperCase(), record[4], record[5].toUpperCase(), record[6], record[7].toUpperCase(), record[8]
]])
var html = HtmlService.createHtmlOutput("<h4>Entry Accepted</h4><p>Close sidebar to continue or add another employee.</p>")
.setWidth(300)
.setHeight(125);
ui.showModalDialog(html, "Success!")
}
else if (checkId(record[2].toString())) {
var html = HtmlService.createHtmlOutput("<h4>User id# already exists</h4><p>Please choose different id#</p>")
.setWidth(200)
.setHeight(75);
ui.showModalDialog(html, "Warning!")
}
else if (checkJob(record[3])) {
var html = HtmlService.createHtmlOutput("<h4>Job Code does not exitst</h4><p>Please choose a valid job code.<br>*Case sensitive</p>")
.setWidth(200)
.setHeight(75);
ui.showModalDialog(html, "Warning!")
}
else {
var html = HtmlService.createHtmlOutput("<h4>Unspecified error</h4><p>Please contact support.</p>")
.setWidth(200)
.setHeight(75);
ui.showModalDialog(html, "Warning!")
}
array_target.setValue(array_formula)
}
// checks if an id# already exists
function checkId(num) {
var result = false;
var current_ids = ws.getRange(2, 4, ws.getLastRow(), 1).getValues();
for (id = 0; id < current_ids.length; id++) {
if (current_ids[id].toString() == num.toString()) {
result = true
}
}
return result
}
// checks if a job code exists
function checkJob(job) {
var result = false;
var current_jobs = setup.getRange(2, 3, setup.getLastRow(), 1).getValues();
for (job = 0; job < current_jobs.length; job++) {
if (current_jobs[job] == job) {
result = true
}
}
return result
}
function editEmp() {
Logger.log("editting an employee")
}
function delEmp() {
Logger.log("deleting an employee")
}
I'd like to utilize the include("page") function to keep the style, script, and html separate and readable. What am I missing here?
I think it has something to do with how the data is loaded and evaluated, but don't see how to apply a fix.
When I split apart the code over to the scriplet include function, I looked into using a window.onload eventhandler to re-evaluate the code, but I don't know if that is the best approach with a form.
</details>
# 答案1
**得分**: 0
我相信你的目标如下。
- 你想要解决当前的问题`Uncaught TypeError: Cannot read properties of null (reading 'value')`。
当我看到你的脚本时,在HTML的顶部,使用了`<div><input id=" fName" type="text" /> First Name</div>`。在这种情况下,`id`是`" fName"`。但是,在你的Javascript中,使用了`let fname = document.getElementById("fName").value`。
我认为你当前的问题`Uncaught TypeError: Cannot read properties of null (reading 'value')`的原因是这个。所以,请按照以下方式进行修改。
### 从:
<div><input id=" fName" type="text" /> First Name</div>
### 到:
<div><input id="fName" type="text" /> First Name</div>
<details>
<summary>英文:</summary>
I believe your goal is as follows.
- You want to remove your current issue of `Uncaught TypeError: Cannot read properties of null (reading 'value')`.
When I saw your script, at the top HTML, `<div><input id=" fName" type="text" /> First Name</div>` is used. In this case, `id` is `" fName"`. But, in your Javascript, `let fname = document.getElementById("fName").value` is used.
I think that the reason for your current issue of `Uncaught TypeError: Cannot read properties of null (reading 'value')` is due to this. So, please modify as follows.
### From:
<div><input id=" fName" type="text" /> First Name</div>
### To:
<div><input id="fName" type="text" /> First Name</div>
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论