HTML form- check boxes programmatically - html

I am working on a Google Add-On in Google Apps Script, and I am attempting to make an HTML Form as a sidebar, the code of which is here:
<body onload="google.script.run.onSettingsOpen()">
<form id="baseSettings" onsubmit="event.preventDefault(); google.script.run.processForm(this); google.script.host.close()">
<h2>What settings would you like to be on? Please select all that apply.</h2>
<br>
<input type="checkbox" name="checks" value="spaces" id="spaces">Double spaces
<br>
<input type="checkbox" name="checks" value="punctuation" id="punctuation">Punctuation outside of quotes
<br>
<input type="checkbox" name="checks" value="caps" id="caps">Capitilazation at beginning of sentences
<br>
<input type="checkbox" name="checks" value="contractions" id="contractions">Contractions
<br>
<input type="checkbox" name="checks" value="numbers" id="numbers">Small numbers
<br>
<input type="checkbox" name="checks" value="repWords" id="repWords">Repeated words
<br>
<br>
<input type="submit" value="Submit">
</form>
</body>
I am attempting to use User Properties to keep track of which boxes should be checked for this form (it is a settings panel). The user properties all start as true, and can be only true or false- no other values. I have written the following code to get the check boxes to reflect what has been previously selected by the user for their preferences:
function onSettingsOpen()
{
populateData ();
initializePreferences();
document.getElementById(propsList[1]).checked = (allPreferences.getProperty(propsList[1]) === "true");
document.getElementById(propsList[2]).checked = (allPreferences.getProperty(propsList[2]) === "true");
document.getElementById(propsList[3]).checked = (allPreferences.getProperty(propsList[3]) === "true");
document.getElementById(propsList[4]).checked = (allPreferences.getProperty(propsList[4]) === "true");
document.getElementById(propsList[5]).checked = (allPreferences.getProperty(propsList[5]) === "true");
}
The propsList array is as follows:
var propsList = ["spaces", "punctuation", "caps", "contractions", "numbers", "repWords"];
Here is the processForm function:
function processForm(formObject)
{
var ui = DocumentApp.getUi();
var results = JSON.stringify(formObject.checks);
for (var i = 0; i < 6; i++)
{
if (allPreferences.getProperty(allPros[i]) === "false" && results.includes(allProps[i]))
{
allPreferences.setProperty(allProps[i], true)
}
else if (allPreferences.getProperty(allPros[i]) === "true" && !results.includes(allProps[i]))
{
allPreferences.setProperty(allProps[i], false)
}
}
}
And here is the populateData() function:
function populateData ()
{
if (doc == undefined)
{
doc = DocumentApp.getActiveDocument();
bod = doc.getBody();
docTxt = bod.getText();
toEdit = bod.editAsText();
paragraphs = bod.getParagraphs();
ui = DocumentApp.getUi();
allPreferences = PropertiesService.getUserProperties();
}
}
My current issue is that I am getting an error message reading: "Execution failed: ReferenceError: "document" is not defined." I'm not sure what to do about this. I have tried it in JQuery as well, to no avail. All I want to do is be able to access the "checked" attribute of my form and edit it programatically. Any help appreciated, thanks

Related

HTML form radio conditional

¡Hello! I need to make this range start working when the check is pressed ¿Can I get some help? Thanks
`
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="si" name="nivel" onclick="myFunction()"><label for="si">Si</label>
<input type="range"id="tickmarks" disabled="disabled" />
<datalist id="tickmarks">
<option value="bajo" label="Bajo"></option>
<option value="medio" label="Medio"></option>
<option value="alto" label="Alto"></option>
</datalist>
<script>
function myFunction() {
var nivel = document.getElementById("si");
var tickmarks = document.getElementById("tickmarks");
if (nivel.checked == true){
tickmarks.style.display = "block";
} else {
tickmarks.style.display = "none";
}
}
</script>
</body>
</html>
`
I tried to press the checkbox to make the range appear and it could be selected but when it appears it is disabled.
You can control whether an element is disabled by setting the element's disabled attribute to true/false.
<input type="checkbox" id="si" name="nivel" onclick="myFunction()">
<input type="range" id="tickmarks" disabled>
function myFunction() {
const nivel = document.getElementById("si");
const tickmarks = document.getElementById("tickmarks");
if (nivel.checked == true) {
tickmarks.disabled = false;
} else {
tickmarks.disabled = true;
}
}

Script for selecting sheets using control

I have in a spreadsheet, a MENU with buttons linked to other sheets.
Since I have many sheets, I want that when selecting a button it is the same for a group of those sheets.
Ex: btn "Enter approved teachers", there are 4 sheets that are to enter that data, each one corresponds to a different area.
That when I click on this button, I skip a "popup" that shows me a list of that sheets and lets me select it with an "OK".
The part of selecting the sheet with a script is easy to do with a youtube tutorial, but the control of sheets and selection I can not find anywhere.
I haven't been able to try anything, as I don't have experience coding in Apps Script or Js.
Hopefully this is close to what you are looking for:
This a dialog I use for selecting which files I wish to backup from my spreadsheets.
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
input {margin: 2px 5px 2px 0;}
#btn3,#btn4{display:none}
</style>
</head>
<body>
<form>
<input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />
<br /><input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />
<div id="shts"></div>
<br /><input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
<input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>
<br /><input type="checkbox" id="files" name="saveFiles" checked /><label for="files">Save Files</label>
<br /><input type="checkbox" id="json" name="saveJson" checked /><label for="json">Save JSON</label>
<br /><input type="button" value="Submit" onClick="backupFiles();" />
</form>
<script>
function getFileNames() {
const scriptid = document.getElementById("scr").value;
google.script.run
.withSuccessHandler((names) => {
document.getElementById('btn3').style.display = "inline";
document.getElementById('btn4').style.display = "inline";
names.forEach((name,i) => {
let br = document.createElement("br");
let cb = document.createElement("input");
cb.type = "checkbox";
cb.id = `cb${i}`;
cb.name = `cb${i}`;
cb.className = "cbx";
cb.value = `${name}`;
cb.checked = true;
let lbl = document.createElement("label");
lbl.htmlFor = `cb${i}`;
lbl.appendChild(document.createTextNode(`${name}`));
document.getElementById("shts").appendChild(cb);
document.getElementById("shts").appendChild(lbl);
document.getElementById("shts").appendChild(br);
});
})
.getAllFileNames({scriptId:scriptid});
}
function unCheckAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length);
for(let i =0;i<btns.length;i++) {
btns[i].checked = false;
}
}
function checkAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length)
for(let i = 0;i<btns.length;i++) {
btns[i].checked = true;
}
}
function backupFiles() {
console.log('backupFiles');
sObj = {};
sObj.script = document.getElementById('scr').value;
sObj.folder = document.getElementById('fldr').value;
sObj.saveJson = document.getElementById('json').checked?'on':'';
sObj.saveFiles = document.getElementById('files').checked?'on':'';
sObj.selected = [];
console.log("1");
const cbs = document.getElementsByClassName("cbx");
let selected = [];
for(let i = 0;i<cbs.length; i++) {
let cb = cbs[i];
if(cb.checked) {
sObj.selected.push(cb.value)
}
}
console.log("2");
google.script.run
.withSuccessHandler(function(obj){google.script.host.close();})
.scriptFilesBackup(sObj);
console.log(JSON.stringify(sObj));
}
</script>
</body>
</html>
This is what the dialog looks like:

Apps script return values from server function to html form

I need help of professionals at Apps script. I have the project implemented by web-app.
I wrote script on server-part
var url = "https://docs.google.com/spreadsheets/d/1s8l-8N8dI-GGJi_mmYs2f_88VBcnzWfv3YHgk1HvIh0/edit?usp=sharing";
var sprSRCH = SpreadsheetApp.openByUrl(url);
let sheetSRCHSSCC = sprSRCH.getSheetByName("PUTAWAY_TO");
function GetQ(){
var QPLAN = sheetSRCHSSCC.getRange("M2:M").getValues().filter(String).length;
var myArray = sheetSRCHSSCC.getRange("O2:O" + (QPLAN + 1)).getValues();
var QFACT = 0;
for (i = 0; i < myArray.length; i++) {
if (myArray[i] != "") {
QFACT += 1
}
}
}
I need to return values from this function to inputs:
QFACT to FACT
QPLAN to PLAN
<div class="input-field col s3">
<input disabled value="" id="PLAN" type="text" >
<label for="disabled">PLAN</label>
</div>
<div class="input-field col s3">
<input disabled value="" id="FACT" type="text" >
<label for="disabled">FACT</label>
</div>
I will be grateful for the help. I'm new at this))
If you are using Apps Script deploying Web App, I can see 2 possibilities :
1/ Get data at the loading of the page (and only at the loading) :
In code.gs :
function doGet() {
var tmp = HtmlService.createTemplateFromFile('page');
tmp.QFACT = "hello";
tmp.PLAN = "World!";
return tmp.evaluate();
}
In page.html :
<html>
<body>
<h5><?= QFACT ?></h5>
<h5><?= QPLAN ?></h5>
</body>
</html>
2/ If you need to refresh the data by click button, or something else, you will need to operate diffently :
Add a page-js.html to your project, and bind it at the end of your page.html
<html>
<body>
<h5 id="QFACT"></h5>
<h5 id="QPLAN"></h5>
</body>
<?!= include("page-js"); ?>
</html>
then in your page-js.html :
<script>
function refresh() {
google.script.run.withSuccessHandler(callback).refresh();
}
function callback(e) {
document.getElementById('QPLAN').innerHTML = e.QPLAN;
document.getElementById('QFACT').innerHTML = e.QFACT;
}
</script>
and finally add the refresh() function in your code.gs :
function refresh() {
var obj = {};
obj.QPLAN = "QPLAN";
obj.QFACT = "QFACT";
return obj;
}

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<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);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

Input type=file, restrict to .rpt only

I'm using tag <input type="file" accept="application/x-rpt, magnus-internal/rpt"/> to only allow .rpt files to be uploaded, but it's unsuccessful. User still can upload whatever they want.
What's wrong here? Please help me. Thank you so much.
Put the following script in head
<script type="text/javascript">
function ValidateForm() {
var fileBox = document.getElementById("fileBox");
var val = fileBox.value;
var splittedValue = val.split(".");
//alert(splittedValue.length);
//for (var i = 0; i < splittedValue.length; i++) {
// alert(splittedValue[i]);
//}
var NthElementIndex = splittedValue.length - 1;
var nThElement = splittedValue[NthElementIndex];
if (nThElement != "jpg"
&& nThElement != "rpt") {
alert("Please select valid rpt file");
}
}
</script>
Now Use the following information for id in input tag
<input type="file" id="fileBox" />
<input type="button" onclick="ValidateForm()" value="Validate" />