Reputation: 13
I have created a simple web page using the HTML service in Google Apps Script.
In the code.gs file I have a getData() function which returns a 'students' array.
In the index.html file I have a simple text input box and a student name. In the input box I would like to enter a student's ID number and have the name update based on the 'students' array from the getData() function.
I also have a separate jquery.html file which updates the student name based on the text input. For now I have a sample array with just three students, but I would like to use the 'students' array from the code.gs file.
I've tested everything with the sample array and it's working the way it should. I've also tested the getData() function directly in the index.html file using and it also is working properly.
Is there a way to use the 'students' array from the getData() function in my code.gs file in my jquery.html file?
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('index.html').evaluate().setTitle("Student Records");
}
function getData() {
var studentSs = SpreadsheetApp.openById("<-- spreadsheet Id -->");
var studentSheet = studentSs.getSheets()[0];
var studentDataRange = studentSheet.getDataRange();
var students = studentDataRange.getValues();
return students;
}
index.html
<input type="text" id="student-id">
<div class="student">
<h2>student name</h2>
</div>
jquery.html
$(document).ready(function() {
var students = [
[1, "John"],
[2, "Sue"],
[3, "Bill"]
];
$("#student-id").on("keyup", function() {
var studentId = $(this).val();
$.each(students, function(i) {
if (studentId == students[i][0]) {
$("h2").text(students[i][1]);
return false;
} else {
$("h2").text("That student doesn't exist");
}
});
});
});
UPDATE: I finally found a solution. I updated the jquery.html file to this:
< script >
var students;
function onSuccess(array) {
students = array;
}
google.script.run.withSuccessHandler(onSuccess).getData();
$(document).ready(function() {
$("#student-id").on("keyup", function() {
var studentId = $(this).val();
$.each(students, function(i) {
if (studentId == students[i][0]) {
$("h2").text(students[i][1]);
return false;
} else {
$("h2").text("That student doesn't exist");
}
});
});
});
< /script>
Upvotes: 0
Views: 2036
Reputation: 7387
Two options for this:
First, modify your getData() function to JSON encode your data:
return JSON.stringify(students);
See: What is JSON and why would I use it?
Then, you can either call your Apps Script function from directly inside your template
var students = <?!= getData(); ?>;
Or you can pass the data into your template from doGet():
function doGet() {
var template = HtmlService.createTemplateFromFile('index.html');
template.students = getData();
return template.evaluate().setTitle("Student Records");
}
And in your template:
var students = <?!=students?>;
See: https://developers.google.com/apps-script/guides/html/templates#pushing_variables_to_templates
Upvotes: 1