Put array values into different html textboxes - javascript

I need to publish individuals' exam results from a google sheet. I have found some code and created another HTML page which now gives me the required result properly if I click the SHOW link. The app script is :
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1L1Qu6QCaDucr4Jy5eOAnQkX-wpYjz6eevqAMzBc72iQ/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");
function doGet(e){
return search(e) ;
}
function doPost(e){
return search(e) ;
}
function search(e) {
var id = e.parameter.id;
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
});
var content = JSON.stringify(values);
return ContentService.createTextOutput(content).setMimeType(
ContentService.MimeType.TEXT
);
}
and the HTML is :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txtName"/>
SHOW
</body>
</html>
It gives the result in an array like [[ROLL, "Name", MARKS1, MARKS2, MARKS3...]]. Now I need to use these values at an HTML page like
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>INSTITUTE NAME</h1>
Name <input type="text" id="name"/><br>
Roll <input type="text" id="roll"/><br>
Subject 1 <input type="text" id="sub1"/><br>
Subject 2 <input type="text" id="sub2"/><br>
Subject 3 <input type="text" id="sub3"/><br>
Subject 4 <input type="text" id="sub4"/><br>
Subject 5 <input type="text" id="sub5"/><br>
</body>
</html>
I mean like
What should I do?

You don't need two HTML, you can do the entire process with one HTML using google.script.run [1] to communicate your code.gs with the Index.html, and update it with the data from the spreadsheet.
Just create an Index.html file with this:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>INSTITUTE NAME</h1>
Name <input type="text" id="name"/><br>
Roll <input type="text" id="roll"/><br>
Subject 1 <input type="text" id="sub1"/><br>
Subject 2 <input type="text" id="sub2"/><br>
Subject 3 <input type="text" id="sub3"/><br>
Subject 4 <input type="text" id="sub4"/><br>
Subject 5 <input type="text" id="sub5"/><br>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
document.getElementById('sub1').value = values[2];
document.getElementById('sub2').value = values[3];
document.getElementById('sub3').value = values[4];
document.getElementById('sub4').value = values[5];
document.getElementById('sub5').value = values[6];
}
</script>
</html>
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index');
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1L1Qu6QCaDucr4Jy5eOAnQkX-wpYjz6eevqAMzBc72iQ/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
});
return values[0];
}
Deploy the application and you can access to it with the URL.
[1] https://developers.google.com/apps-script/guides/html/communication

I am assuming that the results array is like the one you told. I think the best way to handle these is creating a dom node and appending to a container element and wrapping that logic to a looping function. Here's my example:
const resultElement = (value) => {
let wrapper = document.createElement("div");
//ROLL
let rollElement = document.createElement("input");
rollElement.setAttribute("type","text");
rollElement.value = value[0];
wrapper.appendChild(rollElement);
//Name
let nameElement = document.createElement("input");
nameElement.setAttribute("type","text");
nameElement.value = value[1];
wrapper.appendChild(nameElement);
//Marks
for(let i = 2; i < value.length; i++) {
let markElement = document.createElement("input");
markElement.setAttribute("type","text");
markElement.value = value[i];
markElement.setAttribute("id", ("mark_"+i));
wrapper.appendChild(markElement);
}
return wrapper;
}
const handleAllValues = (values) => {
let container = document.getElementById("container");
for(let i = 0;i<values.length;i++) {
let el = resultElement(values[i]);
container.appendChild(el);
}
}
and you should have an element with id="container" in your html.

Related

How to add reset button in the dialog in Google Sheets

I'm new to the scripting, but from what I have learned from this website, I have put together a check book balancesheet in google sheets.
I have a function "AddCheck" attached to the button on one of the cell. What it does is - opens a dialog box where I enter check details, like Date, Invoice number, amount and vendor's name. Then I click the submit button and Google sheets creates a row and adds those values.
My Question is how do I add a button next to the submit button that will allow me to add the New check details without leaving the dialog box. So that it will add the values to the cells and will clear the dialog box for another Entry.
This is my AddCheck function
function AddCheck() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('3:3').activate();
spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 1);
spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
spreadsheet.getRange('A3').activate();
spreadsheet.getCurrentCell().setFormula('=A4+1');
spreadsheet.getRange('G3').activate();
spreadsheet.getCurrentCell().setValue('Pending');
spreadsheet.getRange('B3').activate();
fncOpenMyDialog()
};
This is my HTML dialog file
<!DOCTYPE html>
<html>
<body>
<form>
<label for="Date">Date :</label>
<input type='date' name='Date' id="Date" required="required"/>
<br>
<label for="Invoice">Invoice</label>
<input type='text' name='Invoice' id="Invoice" required="required"/>
<label for="Amount">Amount</label>
<input type='text' name='Amount' id="Amount" required="required"/>
<label for="Company">Company</label>
<select name="Class" id="vendor-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("vendor-selector");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.text = selectList[i][0];
select.add(option);
}
}
).getSelectList();
}());
</script>
</select>
<input type="submit" value="Submit" onclick="myFunction(this.parentNode)">
</form>
<p id="CompanyName"></p>
<script>
function myFunction(obj) {
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(() => google.script.host.close())
.functionToRunOnFormSubmit(obj);
}
</script>
</body>
</html>
This Function calls the Dialog
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('CheckDetails')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(250);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Check Details');
};
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var ss = SpreadsheetApp.getActive();
ss.getSheetByName("Checks").getRange(3,3).setValues([[fromInputForm.Class]]);
ss.getSheetByName("Checks").getRange(3,2).setValues([[fromInputForm.Date]]);
ss.getSheetByName("Checks").getRange(3,4).setValues([[fromInputForm.Invoice]]);
ss.getSheetByName("Checks").getRange(3,6).setValues([[fromInputForm.Amount]]);
};
and this Function gets the List of vendors from Sheet2
function getSelectList()
{
var sheet = SpreadsheetApp.openById("141mlnxJBjepKxYCGXHFhz5IIEVnp6T2DDsb_uRgnZzY").getSheetByName('Sheet2');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A2:A" + lastRow);
var data = myRange.getValues();
Logger.log("Data = " + data);
return data;
};
function doGet()
{
return HtmlService.createHtmlOutputFromFile('CheckDetails');
}
Thank you for your help.
In order to implement this "Submit & Continue" feature, you only need to change the front-end code so that:
There is a new button.
Upon clicking the new button, the same back-end (GAS) code gets executed.
The dialog does not get closed after the GAS code execution, but the input elements are reset.
Code modifications
Add an id to the form tag so that it may be easily selected.
<form id="CheckDetailsForm">
Create a "Submit & Continue" button in your HTML. Assign an id to it so that it may be easily selected.
<input type="submit" value="Submit and continue" id="SubmitAndContinueInput" />
Within the script tag, add an event listener to the newly created button.
document.getElementById("SubmitAndContinueInput").addEventListener("click", myFunctionContinue);
Add the handler function for the newly created button's onclick event. This function will be very similar as the one you are using but: It will use the preventDefault to avoid the form being incorrectly sent and will clear the form data upon submission.
function clearForm() {
document.getElementById('Date').value = "";
document.getElementById('Invoice').value = "";
document.getElementById('Amount').value = "";
}
function myFunctionContinue(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(clearForm)
.functionToRunOnFormSubmit(obj);
}
Example dialog:
Edit
Handling "submit and continue" new rows:
Remove the row-insertion functionality from AddCheck(). We will handle this logic afterwards:
function AddCheck() {
fncOpenMyDialog();
}
Modify the functionToRunOnFormSubmit() function so that it handles the row-insertion logic. I have also cleaned up the code a little bit. It would look like the following:
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var sheet = SpreadsheetApp.getActive().getSheetByName("Checks");
sheet.insertRowBefore(3);
sheet.getRange("A3").setFormula("=A4+1");
sheet.getRange("B3").setValue(fromInputForm.Date);
sheet.getRange("C3").setValue(fromInputForm.Class);
sheet.getRange("D3").setValue(fromInputForm.Invoice);
sheet.getRange("F3").setValue(fromInputForm.Amount);
sheet.getRange("G3").setValue("Pending");
}
Full code
CheckDetails.html
<!DOCTYPE html>
<html>
<body>
<form id="CheckDetailsForm">
<label for="Date">Date :</label>
<input type='date' name='Date' id="Date" required="required"/>
<br>
<label for="Invoice">Invoice</label>
<input type='text' name='Invoice' id="Invoice" required="required"/>
<label for="Amount">Amount</label>
<input type='text' name='Amount' id="Amount" required="required"/>
<label for="Company">Company</label>
<select name="Class" id="vendor-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("vendor-selector");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.text = selectList[i][0];
select.add(option);
}
}
).getSelectList();
}());
</script>
</select>
<input type="submit" value="Submit" id="SubmitInput" />
<input type="submit" value="Submit and continue" id="SubmitAndContinueInput" />
</form>
<p id="CompanyName"></p>
<script>
document.getElementById("SubmitInput").addEventListener("click", myFunction);
document.getElementById("SubmitAndContinueInput").addEventListener("click", myFunctionContinue);
function clearForm() {
document.getElementById('Date').value = "";
document.getElementById('Invoice').value = "";
document.getElementById('Amount').value = "";
}
function myFunction(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(() => google.script.host.close())
.functionToRunOnFormSubmit(obj);
}
function myFunctionContinue(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(clearForm)
.functionToRunOnFormSubmit(obj);
}
</script>
</body>
</html>
Code.gs
function AddCheck() {
fncOpenMyDialog()
}
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('CheckDetails')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(250);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Check Details');
}
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var sheet = SpreadsheetApp.getActive().getSheetByName("Checks");
sheet.insertRowBefore(3);
sheet.getRange("A3").setFormula("=A4+1");
sheet.getRange("B3").setValue(fromInputForm.Date);
sheet.getRange("C3").setValue(fromInputForm.Class);
sheet.getRange("D3").setValue(fromInputForm.Invoice);
sheet.getRange("F3").setValue(fromInputForm.Amount);
sheet.getRange("G3").setValue("Pending");
}
function getSelectList() {
var sheet = SpreadsheetApp.openById("141mlnxJBjepKxYCGXHFhz5IIEVnp6T2DDsb_uRgnZzY").getSheetByName('Sheet2');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A2:A" + lastRow);
var data = myRange.getValues();
Logger.log("Data = " + data);
return data;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('CheckDetails');
}

Output filter results into a text box

I'm trying to create a web apps script with a field that accepts user input and returns the result(s). I need it to list all the results associated with the input query.
Things I've tried doing:
I've assigned an actual order number to orderInput and I was able to get the results I wanted it to return using Logger.log(orderMatch) so I know it works.
I wasn't sure if I was running into a formatting issue so I tried converting orderInput to a string with orderInput.toString() and that didn't work.
At first I was trying to display it in a disabled input field and that didn't work so I tried using a textarea but that didn't work either.
I've also tried moving the document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields(); in various places between return item[0] === orderInput
});
I was using document.getElementById("orderNumber").addEventListener("change",orderLookup); to trigger the script from running but I also tried creating a button with onclick="orderLookup()" but that didn't work.
This is my script:
function orderLookup() {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var originalSheet = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderInput = document.getElementById("orderNumber").value;
var orderMatch = originalSheet.filter(function(item) {
return item[0] === orderInput
});
document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields();
}
As for my HTML:
<div class="input-field col s2">
<input value="" id="orderNumber" type="text" class="validate">
<label class="active" for="orderNumber">Enter Order Number</label>
</div>
<center style="float:left;margin-left:0px;margin-top:0px;">
<h6><b>Results</b></h6>
<textarea id="orderResults" rows="10" cols="45" disabled="disabled" style="width:100%; height:auto"></textarea>
</center>
Well it looks to me like your mixing server side functions with client side functions and I'm guessing that since you provide html code and script that you trying to run is client side.
function orderLookup() {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);//Server side function
var ws = ss.getSheetByName("Orders");//Server side function
var originalSheet = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();//Server Side function
var orderInput = document.getElementById("orderNumber").value;//Client Side Function
var orderMatch = originalSheet.filter(function(item) {return item[0]===orderInput});//could be either
document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields();//dont know
}
Assuming that:
You want to look for the data in the sheet when Enter Order Number is clicked.
You want to look for rows where first column matches the input you provided.
You want all the data in the row to show up in the <textarea> element.
A possible solution would be the following:
Create an onclick event in the label, which will run a function on the client side:
<label class="active" for="orderNumber" onclick="search()">Enter Order Number</label>
Next, the following function is run by the onclick event. This function calls a server-side function (orderLookup) which will look for matching data in the sheet and return the results.
function search() {
var input = document.getElementById("orderNumber").value;
google.script.run.withSuccessHandler(showResults).orderLookup(input);
}
Here is function orderLookup:
function orderLookup(input) {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var values = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderMatch = values.filter(function(item) {
return item[0] === input
});
return orderMatch;
}
If orderLookup returns a value, another client-side function will run, which will get the matching data as a parameter, and will write it to the <textarea>:
function showResults(orderMatch) {
var matches = "";
for(var i = 0; i < orderMatch.length; i++) {
matches = matches.concat(orderMatch[i], "\n");
}
document.getElementById("orderResults").value = matches;
}
So, full code would be the following:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div class="input-field col s2">
<input value="" id="orderNumber" type="text" class="validate">
<label class="active" for="orderNumber" onclick="search()">Enter Order Number</label>
</div>
<center style="float:left;margin-left:0px;margin-top:0px;">
<h6><b>Results</b></h6>
<textarea id="orderResults" rows="10" cols="45" disabled="disabled" style="width:100%; height:auto"></textarea>
</center>
</body>
<script>
function search() {
var input = document.getElementById("orderNumber").value;
google.script.run.withSuccessHandler(showResults).orderLookup(input);
}
function showResults(orderMatch) {
var matches = "";
for(var i = 0; i < orderMatch.length; i++) {
matches = matches.concat(orderMatch[i], "\n");
}
document.getElementById("orderResults").value = matches;
}
</script>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function orderLookup(input) {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var values = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderMatch = values.filter(function(item) {
return item[0] === input;
});
return orderMatch;
}
I hope this is what you wanted to accomplish.

Omitting the fields with no value

I need to publish exam result from a Google sheet. The search button shows the marks obtained perfectly if roll no is provided at the box but I need to omit the fields with no value like Subject 3, 5 etc. with their textbox from the html page
Here is the sheet I'm using and the code I'm using ...
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/16IH3yKJjLwM9XA0c4_BN5MVQSKh8hV7gR6_kLLfe8to/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
});
return values[0];
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
.hidden {
display:none;
}
</style>
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
Name <input type="text" id="name"/><br>
Roll <input type="text" id="roll"/><br>
Subject 1 <input type="text" id="sub1"/><br>
Subject 2 <input type="text" id="sub2"/><br>
Subject 3 <input type="text" id="sub3"/><br>
Subject 4 <input type="text" id="sub4"/><br>
Subject 5 <input type="text" id="sub5"/><br>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
document.getElementById('sub1').value = values[2];
document.getElementById('sub2').value = values[3];
document.getElementById('sub3').value = values[4];
document.getElementById('sub4').value = values[5];
document.getElementById('sub5').value = values[6];
}
</script>
</html>
I need to omit the Subject name and the text box with no value from the HTML page. And "Nothing Found" should be shown if a roll searched which is not in the table. It's not required but will be good if the Subject names come from sheet's row 1.
What should I do?
There are two ways to go about this:
Create your HTML on the server side (as #Cooper said)
Manipulate your HTML with JavaScript
To create your HTML on the server side you can use string and "write" the html automatically.
Then your functions will be something like this:
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(response) {
document.getElementById("divid").innerHTML=html
});
If you absolutely want to manipulate the HTML on the client-side, you will use something like this:
function toggleElement(id) {
var td = document.getElementById(id).parentElement;
var tr = td.parentElement;
tr.classList.toggle("hidden");
}
the usage is like so:
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
}
and then you will have some css that does this:
.hidden {
display:none;
}
Edit:
This is how you implement the first solution:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
<div id="dataDiv"></div>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
console.log(values);
document.getElementById("dataDiv").innerHTML=values
}
</script>
</html>
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("SHEETS URL");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
})[0];
var legends = sheet.getRange(1,1,1,sheet.getMaxColumns()).getValues()[0];
return createHTML(legends, values);
}
function createHTML(legends, values) {
Logger.log(legends);
var htmlResult = "";
for (var i=0; i<values.length; i++) {
if (values[i]!=null && values[i]!=="") {
htmlResult += '<div class="field">' + (legends[i]+"").replace("Sub", "Subject ") + '<input type="text" id="sub1" value="'+values[i]+'"></div>';
}
}
return htmlResult;
}
Hope this helps!
Here's a simple example of a complete solution of your problem done mostly server side.
I like do it this way because I like to be able to use Utilities.formatString().
Server Functions:
File: aq3.gs:
function search(sObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getDataRange();
var vA=rg.getValues();
var hA=vA[0];
var dObj={dA:[]};
for(var i=1;i<vA.length;i++) {
if(vA[i][0]==sObj.roll) {
var row=vA[i];
for(var j=0;j<hA.length;j++) {
dObj[hA[j]]=row[j];
}
break;
}
}
var html="<style>input{margin:2px 5px 0 2px}</style>";
for(var i=0;i<row.length;i++) {
if(dObj[hA[i]]) {
html+=Utilities.formatString('<br /><input id="txt-%s" type="text" value="%s" /><label for="txt-%s">%s</label>',i,dObj[hA[i]],i,hA[i]);
}
}
sObj['results']=html;
return sObj;
}
Run the below function to get the dialog running. The enter the roll you wish to see in the search box and click the search button. You will get only the boxes that have data.
function launchExamResultsSearchDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq5');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Exam Results");
}
The html:
File: aq5.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function search() {
var text=$('#srchtext').val();
google.script.run
.withSuccessHandler(function(sObj) {
document.getElementById("results").innerHTML=sObj.results;
})
.search({roll:text});
}
console.log("My Code");
</script>
</head>
<body>
<input type="text" id="srchtext" /><input type="button" value="Search" onClick="search();" />
<div id="results"></div>
</body>
</html>
This is what the dialog looks like:
You can just keep changing the search roll number and the dialog will replace the data with the new data. You can control the subjects by changing the headers.
Client To Server Communication
Utilities.formatString()

How to pass a form data to a client side function (google.scripts.run) and return result to HTML?

I'm trying to take an ID from a form and run that ID against a function in CODE.gs that checks the spreadsheet for that ID and returns the name back in the HTML. Right now when it runs it gives me an undefined.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
var result
var id
function getName() {
var id = document.getElementById("SearchID").value;
document.getElementById("SearchID").value = "";
var result = google.script.run.findName(id);
document.getElementById("NameDisp").innerHTML = result;
}
</script>
</head>
<body>
Welcome to Verify. To begin, enter an ID below.<br><br>
Student ID:<input type="text" id="SearchID" name="id" size="10">
<input type="button" name="search" type="submit" value="Go" onclick="getName();";/>
<div id="NameDisp"></div>
<div id="grade"></div>
<br><br>
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
CODE.GS
function findName(empID) {
var ss = SpreadsheetApp.getActive();
var sh = ss.setActiveSheet(ss.getSheetByName('STU401'), true);
var last=ss.getLastRow();
var data=sh.getRange(1,1,last,5).getValues(); // create an array of data from columns A and B
for(nn=0;nn<data.length;++nn){
if (data[nn][0]==empID){break} ;// if a match in column A, break loop
}
var empName = data[nn][4]
return empName
}
google.script.run calls a function asynchronously so you must provide a callback function which will be sent the return value.
You provide the callback using withSuccessHandler as follows:
google.script.run
.withSuccessHandler(function(result) {
// this function is called if the function runs successfully
// and the parameter "result" will have the value returned
// by the findName function
document.getElementById("NameDisp").innerHTML = result;
})
.findName(id);

get value from HTML form with Javascript and then display them on html

This is my first post ever! So I am currently studying front end web development online. I have come across a problem! I am trying to get input from a user HTML form and display those values back on the HTML document. When I do it using javascript work but when using the form it dont.
see my code in codepen : http://codepen.io/kevin1616/pen/KdOvwy
My html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contact List</title>
</head>
<body>
<header>
<h1> ContactBook.com </h1>
</header>
<section id="body">
<form method="post">
<input type="text" id="name" ><br>
<input type="text" id="last" ><br>
<input type="text" id="phone" ><br>
<input type="text" id="address" ><br>
<input type="submit" id="create_new_contact" >
</form>
<ol id="people">
</ol>
</section>
<script src="js.js"></script>
</body>
</html>
my javascript
// JavaScript Document
// CONTACTS CONTRUCTOR OBJECT
var contacts = function ( ) {
this.name = [];
this.lastName= [];
this.phoneNumber = [];
this.address= [];
};
contacts.prototype.add = function(name, last, number, address) {// Add method to add contacts
this.name.push(name);
this.lastName.push(last);
this.phoneNumber.push(number);
this.address.push(address);
}
contacts.prototype.toHTML = function (i) {// toHTML method formats how html will be displayed
var htmlString ="<li>";
htmlString +="<p>" + this.name[i] + "<p>";
htmlString +="<p>" + this.lastName[i] + "<p>";
htmlString +="<p>" + this.phoneNumber[i] + "<p>";
htmlString +="<p>" + this.address[i]+ "<p>";
htmlString +="</li>";
return htmlString;
};
contacts.prototype.renderElement = function (list) {// method for sending input to html
for ( var i=0; i < this.name.length; i++) {
list.innerHTML+= this.toHTML(i);
}
};
var addingContact = new contacts();// creating new instance of contructor
addingContact.add("Kevin", "Silvestre" ,"781 582 4449", "26 endicott st");// using the add method to add contacts to my list
var itemsTorender = document.getElementById("people");// select where in the html the elemtents will be rendered
addingContact.renderElement(itemsTorender);// render elements to html
You Just Need A function which call during submit form to get form data that time and show it in list
function saveData(){
var name = document.getElementById("name").value;
var last = document.getElementById("last").value;
var phone = document.getElementById("phone").value;
var address = document.getElementById("address").value;
addingContact.add(name,last ,phone, address);// using
var itemsTorender = document.getElementById("people");// select where in the html
addingContact.renderElement(itemsTorender);// render elements to html
return false; // this will stop default submit of form (because by default form submit on "action" url if no action is define than on same page )
}
and you need to call it like
<form method="post" action="#" onsubmit="return saveData()">
Fiddle

Categories