Automatically generating multiple choice quizzes on google forms - google-apps-script

I am a teacher and need to create lots of multiple choice quizzes like this for my students.
You will see that each multiple choice question has exactly the same format - a question to be uploaded as an image and then followed by 4 multiple choice options - A, B, C and D.
My question is, is there any way to automate this process?
Each batch of questions are inside a googledrive folder and are named '1.png', '2.png', '3.png', etc - these are to be uploaded as images on the google form.
In a separate folder, I have a googlesheet listing all the answers to each question, it looks like this.
So the numbers that match with the answers (letters) in the spreadsheet correspond to the image files (eg. the first row of the spreadsheet above shows that the answer to question 1.png is A)
In a separate folder, I have another googlesheet, with feedback for both incorrect and correct answers which looks like this. Not all questions have feedback.
Is there anyway to automatically generate quizzes from these googlesheets and png files?
Thanks for taking the time to read through all this, and special thanks if you are able to suggest a solution?

Here's a solution to a questioner that wanted to randomly select a given number of questions from a question bank. This doesn't utilize google forms but rather it uses html forms.
Here's the code (your welcome to adapt it):
I had some questions on the code and corrected and problem and went in and updated the code. It's a little more organized and a bit easier to follow...I hope.
Code.gs:
function onOpen() {
SpreadsheetApp.getUi().createMenu('Questions Menu')
.addItem('Questions', 'launchQuestionsDialog')
.addToUi();
}
question.gs
function getQuestions() {
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qnum=cpData.qNum;
var qa=getQAndA();
var qi=getAnswerIndexes();
var html='';
var clr=['#f6d1ac','#c5e9bd'];
for(var i=0;i<qa.length;i++) {
html+=Utilities.formatString('<div id=d%s style="font-weight:bold;background-color:%s;padding:5px;"><span id="q%s">%s</span><input type="hidden" value="%s" class="hiding" />',qa[i][0],clr[i % 2],qa[i][0],qa[i][1],qa[i][0]);
html+=Utilities.formatString('<input type="hidden" value="%s" class="hiding" />',qa[i][0]);
for(var j=qi.firstIdx;j<=qi.lastIdx;j++) {
if(qa[i][j]) {
html+=Utilities.formatString('<br /><input type="radio" name="n%s" value="%s" />%s',qa[i][0],qa[i][j],qa[i][j]);
}
}
html+='</div>'
}
html+='<div id="controls"><br /><input type="button" value="Submit" onClick="recordData();" /></div>';
return {html:html}
}
function launchQuestionsDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('questions').setWidth(800).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The new Questions");
}
function selectTest() {
var qA=selectQuestions(5,24);
Logger.log(qA);
}
function selectQuestionIndexes(n,m) {
var set=[];
do {
var i=Math.floor(Math.random()*(m));
if(set.indexOf(i)==-1) {
set.push(i);
}
}while(set.length<n);
return set;
}
function getCpData() {
var ss=SpreadsheetApp.getActive();
var cpSh=ss.getSheetByName('ControlPanel');
var cpRg=cpSh.getDataRange();
var cpVa=cpRg.getValues();
var qsrcSh=ss.getSheetByName(cpVa[1][0]);
var adesSh=ss.getSheetByName(cpVa[1][1]);
var qnum=cpVa[1][2];
var cpData={'qSrc':cpVa[1][0],'aDes':cpVa[1][1],'qNum':cpVa[1][2]};
return cpData;
}
function getAnswerIndexes() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(getCpData().qSrc);
var rg=sh.getRange(1,1,1,sh.getLastColumn());
var vA=rg.getValues();
var re=/Answer \d{1,2}/i;
var fidx=0;
var lidx=0;
var first=true;
vA[0].forEach(function(e,i){if(String(vA[0][i]).match(re))if(first){fidx=i;first=false;}else{lidx=i;}});
return {'firstIdx':fidx,'lastIdx':lidx};
}
function recordData(responses) {
if(responses) {
var ss=SpreadsheetApp.getActive();
var sheetname=getCpData().aDes;
var sh=ss.getSheetByName(sheetname);
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
responses.forEach(function(e,i){e.splice(0,0,ts);sh.appendRow(e)});
}
return true;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('questions');
}
function getQAndA() {
var qa=[];
var cma=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qsrcSh=ss.getSheetByName(cpData.qSrc);
var qsrcRg=qsrcSh.getRange(2,1,qsrcSh.getLastRow()-1,qsrcSh.getLastColumn());
var qsrcVa=qsrcRg.getValues();
var qs=selectQuestionIndexes(cpData.qNum,qsrcVa.length);
var aIdxs=getAnswerIndexes();
for(var i=0;i<qsrcVa.length;i++) {
var qas='';
if(qs.indexOf(i)>-1) {
qas+=qsrcVa[i][0] + cma + qsrcVa[i][1];
for(j=aIdxs.firstIdx;j<=aIdxs.lastIdx;j++) {
if(qsrcVa[i][j]) {
qas+= cma + qsrcVa[i][j];
}
}
qa.push(qas.split(cma));
}
}
return qa;
}
questions.html:
<!DOCTYPE html>
<html>
<head>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>-->
<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() {
google.script.run
.withSuccessHandler(function(hObj){
$('#container').html(hObj.html);
})
.getQuestions();
});
function recordData() {
var responses=[];
var cm=',';
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++) {
var id=divs[i].getAttribute(['id']);
var qnum=$('div#' + id + ' ' + 'input.hiding').val();
//var question=document.getElementById(id).innerHTML;
var question=$('#q' + qnum ).text();
var answer=$('input[name="n' + qnum + '"]:checked').val();
if(id!='controls') {
if(!answer) {
window.alert('You did not answer question number ' + Number(i+1) + '. It is a requirement of this survey that all questions must be answered.' );
return;
}else {
var end='is near';
var s=qnum + cm + question + cm + answer;
responses.push(s.split(cm));
}
}
}
google.script.run
.withSuccessHandler(displayThanks)
.recordData(responses);
}
function displayThanks() {
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++) {
divs[i].style.cssText="display:none;text-align:center";
}
var elemDiv = document.createElement('div');
elemDiv.innerHTML="<br /><h1>Thank You For Your Participation in This Survey</h1>";
document.body.appendChild(elemDiv);
}
console.log('My Code');
</script>
<style>
#reply{display:none;}
#collect{display:block;}
body {
background-image: url("http://myrabridgforth.com/wp-content/uploads/blue-sky-clouds.jpg");
background-color: #ffffff;
background-repeat: no-repeat;
background-position: left bottom;
}
</style>
</head>
<body>
<div id="container">
</div>
</body>
</html>
Here's what the various tabs on the spreadsheet look like:
The ControlPanel Tab:
The QuestionBank Tab:
The Test1 Tab:
Hopefully this will be of some value to you.

To over-come the problem in high densely populated area
ultra dense network is suggested. Ultra dense network
maintain a constant connectivity, data speed in highly
populated area.

Related

I would like to create a dropdown list in appscript but it dosent work

i would like to create a dropdown list in my webapp, but it doesn't show any value. Could you help me to check? this is the code I found on another website.
I would like to set the dropdown list content as a colunm in a sheet name as "Stafflist". And the first column is different staff name, for example, Peter, Jack, Alex, David, Mary, Jane
What should I do? Thank you
here is the code(gs.code)
function test() {
try {
var output = HtmlService.createHtmlOutputFromFile('HTML_Sidebar');
SpreadsheetApp.getUi().showSidebar(output);
}
catch(err) {
Logger.log(err);
}
}
function getSheets() {
try {
var sheets = SpreadsheetApp.openById("1ZiY2abk8tZcJ_CgCELl2po1yGFnxeCO50tRtBqAN7kE").getSheetByName("Staffname");
var names = sheets.getRange(1,1,sheets.getRange("A1").getDataRegion().getLastRow(),1).getValues();
for( var i=0; i<sheets.length; i++ ) {
names.push(sheets[i].getName());
}
return names;
}
catch(err) {
Logger.log(err);
}
}
function changeSheet(name) {
try {
var spread = SpreadsheetApp.openById("id");
var sheet = spread.getSheetByName("Staffname");
SpreadsheetApp.getActiveSpreadsheet().setActiveSheet(sheet);
}
catch(err) {
Logger.log(err);
}
}
Here is the HTML
<form>
///html dropdown list
<label style="font-size:16pt">Please choose your name:</label>
<select id="mySelect" onchange="selectChange(this)">
</select>
<script>
function selectChange(select) {
google.script.run.changeSheet(select.value);
}
function sheetNames("Staffname") {
var select = document.getElementById("mySelect");
for( var i=0; i<names.length; i++ ) {
var option = document.createElement("option");
option.text = names[i];
select.add(option);
}
}
(function () { google.script.run.withSuccessHandler(sheetNames).getSheets(); }());
</script>

Count and print the number of tags in a google docs

I have a gDocs document with a number of tags like:
[open]
[draft]
[completed]
I’m looking for a way to build a summary at the beginning of the docs:
Number of Open items: X
Number of Completed items: Y
I think I should use regular expressions and google apps scripts but I’m really not familiar with the latest.
Any hint?
This counts the open tags. I'm guessing you can get the rest on your own.
function countOpenTags()
{
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var text=body.getText();
var opens=text.match(/\[open\]/g);
return opens.length;
}
function displayTagCount()
{
var s=Utilities.formatString('There are %s [open] tags in this document', countOpenTags());
var ui=HtmlService.createHtmlOutput(s);
DocumentApp.getUi().showModelessDialog(ui, 'Opens')
}
All in a single dialog.
function countMyTags(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'open';
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var text=body.getText();
var tags=[];
try{
switch(mode)
{
case 'open':
tags=text.match(/\[open\]/g);
break;
case 'draft':
tags=text.match(/\[draft\]/g);
break;
case 'complete':
tags=text.match(/\[complete\]/g);
break;
}
return tags.length;
}
catch(e)
{
return 0;
}
}
function displayTagCount()
{
var s=Utilities.formatString('<br />[open]:%s<br />[draft]:%s<br />[complete]:%s<br /><script>function printDialog(){window.print();}</script><br /><input type="button" value="Print" onClick="printDialog();" /><br /><br /><input type="button" value="Close" onClick="google.script.host.close();" />', countMyTags(),countMyTags('draft'),countMyTags('complete'));
var ui=HtmlService.createHtmlOutput(s);
DocumentApp.getUi().showModelessDialog(ui, 'Tag Summary');
}

How to add conditional questions and logical flow to google form?

I'm currently working on trying to build a google form from a spreadsheet, and I am not sure how to programmatically build conditional questions and branching with the google apps script.
The format of the spreadsheet looks like this:
https://imgur.com/a/bBYkU
And the issue I'm having is figuring how to make it so that questions 1.1 for example goes to 1.2 when you say yes, but goes to question 2 if you say no. I looked into PageNavigationType, but I am iterating through the spreadsheet so I'm unsure how to link to a page I haven't made yet.
Questions from a Question Bank
This does not have a conditional branching based upon previous answers but covers a lot of other stuff. I've done something similar to what you're doing but it was built for a single purpose and not generalized for reprogramming by another user.
Here's an example of a webapp contained in a Spreadsheet that I call Question from a Question Bank. You select the number of questions and it picks that number of questions randomly from a Question Bank. It generates the form, collects the results and stores them on a spreadsheet. I have a video that shows how to use and install it here.
Code.gs file:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('Questions Menu')
.addItem('Questions', 'questionsToHtml')
.addToUi();
}
function selectTest()
{
var qA=selectQuestions(5,24);
Logger.log(qA);
}
function selectQuestionIndexes(n,m)
{
var set=[];
do
{
var i=getRandomIntInclusive(0,m);
if(set.indexOf(i)<0)
{
set.push(i);
}
}while(set.length<n);
return set;
}
function getRandomIntInclusive(min, max)
{
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
function getCpData()
{
var ss=SpreadsheetApp.getActive();
var cpSh=ss.getSheetByName('ControlPanel');
var cpRg=cpSh.getDataRange();
var cpVa=cpRg.getValues();
var qsrcSh=ss.getSheetByName(cpVa[1][0]);
var adesSh=ss.getSheetByName(cpVa[1][1]);
var qnum=cpVa[1][2];
var cpData={'qSrc':cpVa[1][0],'aDes':cpVa[1][1],'qNum':cpVa[1][2]};
return cpData;
}
function getAnswerIndexes()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(getCpData().qSrc);
var rg=sh.getRange(1,1,1,sh.getLastColumn());
var vA=rg.getValues();
var re=/Answer \d{1,2}/i;
var fidx=0;
var lidx=0;
var first=true;
for(var i=0;i<vA[0].length;i++)
{
if(String(vA[0][i]).match(re))
if(first)
{
fidx=i;
first=false;
}
else
{
lidx=i;
}
}
return {'firstIdx':fidx,'lastIdx':lidx};
}
function testResp()
{
var row = [[1,'What is the question?','no'],[2,'What is the question?','no'],[3,'What is the question?','no']];
recordData(row);
}
function recordData(responses)
{
if(responses)
{
var ss=SpreadsheetApp.getActive();
var sheetname=getCpData().aDes;
var sh=ss.getSheetByName(sheetname);
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
for(var i=0;i<responses.length;i++)
{
responses[i].splice(0,0,ts);
sh.appendRow(responses[i]);
}
}
return true;
}
function questionsToHtml(web)
{
var web=(typeof(web)!='undefined')?web:false;
var br='<br />';
var cm=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qnum=cpData.qNum;
var qa=getQAndA();
var qi=getAnswerIndexes();
var s='';
for(var i=0;i<qa.length;i++)
{
//s+='<table>';
//s+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' , qa[i][0],qa[i][1],(qa[i][2])?qa[i][2]:' ',(qa[i][3])?qa[i][3]:' ',(qa[i][4])?qa[i][4]:' ',(qa[i][5])?qa[i][5]:' ');
//s+='</table>';
s+='<div id="d' + qa[i][0] + '" style="font-weight:bold;">' + qa[i][1];
s+='<input type="hidden" value="' + qa[i][0] + '" class="hiding" />';
for(var j=qi.firstIdx;j<=qi.lastIdx;j++)
{
if(qa[i][j])
{
s+=br + '<input type="radio" name="n'+ qa[i][0] +'" value="' + qa[i][j] + '" />' + qa[i][j];
}
}
s+='</div>'
}
s+='<div id="controls">';
s+=br + '<input type="button" value="Submit" onClick="recordData();" />';
//s+=br + '<input type="button" value="Do It Again" onClick="google.script.run.questionsToHtml();" />';
s+='</div>';
s+='</body></html>';
//Logger.log(s);
if(!web)
{
var userInterface=HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(1000).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Current Form')
}
else
{
var output=HtmlService.createHtmlOutputFromFile('htmlToBody').append(s);
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function doGet()
{
return questionsToHtml(true)
}
function getQAndA()
{
var qa=[];
var cma=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qsrcSh=ss.getSheetByName(cpData.qSrc);
var qsrcRg=qsrcSh.getRange(2,1,qsrcSh.getLastRow()-1,qsrcSh.getLastColumn());
var qsrcVa=qsrcRg.getValues();
var qs=selectQuestionIndexes(cpData.qNum,qsrcVa.length-1);
var aIdxs=getAnswerIndexes();
for(var i=0;i<qsrcVa.length;i++)
{
var qas='';
if(qs.indexOf(i)>-1)
{
qas+=qsrcVa[i][0] + cma + qsrcVa[i][1];
for(j=aIdxs.firstIdx;j<=aIdxs.lastIdx;j++)
{
if(qsrcVa[i][j])
{
qas+= cma + qsrcVa[i][j];
}
}
qa.push(qas.split(cma));
}
}
return qa;
}
htmlToBody.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function recordData()
{
var responses=[];
var cm=',';
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++)
{
var id=divs[i].getAttribute(['id']);
var qnum=$('div#' + id + ' ' + 'input.hiding').val();
var question=document.getElementById(id).innerHTML;
var answer=$('input[name="n' + qnum + '"]:checked').val();
if(id!='controls')
{
if(!answer)
{
window.alert('You did not answer question number ' + Number(i+1) + '. It is a requirement of this survey that all questions must be answered.' );
return;
}
else
{
var end='is near';
var s=qnum + cm + question + cm + answer;
responses.push(s.split(cm));
}
}
}
google.script.run
.withSuccessHandler(displayThanks)
.recordData(responses);
}
function displayThanks()
{
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++)
{
divs[i].style.cssText="display:none;text-align:center";
}
var elemDiv = document.createElement('div');
elemDiv.innerHTML="<br /><h1>Thank You For Your Participation in This Survey</h1>";
document.body.appendChild(elemDiv);
}
console.log('My Code Here');
</script>
<style>
#reply{display:none;}
#collect{display:block;}
body {
background-image: url("");
background-color: #ffffff;
background-repeat: no-repeat;
}
</style>
</head>
<body>

Generating a user-specific form with google app script

I'm trying to create a form of 20 or so multiple choice questions (Survey, not right or wrong, if it matters) from a larger bank.
I have seen a few examples on how to generate a form from a google spreadsheet (http://alicekeeler.com/2014/12/12/google-forms-create-a-quiz-from-a-question-bank/ comes close, for example), but my problem goes a bit further in that I need to generate a form with 20 random questions from the bank for each user.
Having searched the web and read a bunch of documentation, I'm still having a hard time trying to determine if it is possible to generate a different form for each viewer using google app script (And if yes, how) or if I should move on to something more robust.
Random Questions from a Question Bank
An example of how you might do a project for making a pseudo random selection of questions from a question bank and displaying them in html format. Upon click a submit request and making sure that all questions have been answered and storing the responses in a spreadsheet.
Here's a link to this code and a video demo of the project.
Here's the Code.gs file:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('Questions Menu')
.addItem('Questions', 'questionsToHtml')
.addToUi();
}
function selectTest()
{
var qA=selectQuestions(5,24);
Logger.log(qA);
}
function selectQuestionIndexes(n,m)
{
var set=[];
do
{
var i=getRandomIntInclusive(0,m);
if(set.indexOf(i)<0)
{
set.push(i);
}
}while(set.length<n);
return set;
}
function getRandomIntInclusive(min, max)
{
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
function getCpData()
{
var ss=SpreadsheetApp.getActive();
var cpSh=ss.getSheetByName('ControlPanel');
var cpRg=cpSh.getDataRange();
var cpVa=cpRg.getValues();
var qsrcSh=ss.getSheetByName(cpVa[1][0]);
var adesSh=ss.getSheetByName(cpVa[1][1]);
var qnum=cpVa[1][2];
var cpData={'qSrc':cpVa[1][0],'aDes':cpVa[1][1],'qNum':cpVa[1][2]};
return cpData;
}
function getAnswerIndexes()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(getCpData().qSrc);
var rg=sh.getRange(1,1,1,sh.getLastColumn());
var vA=rg.getValues();
var re=/Answer \d{1,2}/i;
var fidx=0;
var lidx=0;
var first=true;
for(var i=0;i<vA[0].length;i++)
{
if(String(vA[0][i]).match(re))
if(first)
{
fidx=i;
first=false;
}
else
{
lidx=i;
}
}
return {'firstIdx':fidx,'lastIdx':lidx};
}
function testResp()
{
var row = [[1,'What is the question?','no'],[2,'What is the question?','no'],[3,'What is the question?','no']];
recordData(row);
}
function recordData(responses)
{
if(responses)
{
var ss=SpreadsheetApp.getActive();
var sheetname=getCpData().aDes;
var sh=ss.getSheetByName(sheetname);
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
for(var i=0;i<responses.length;i++)
{
responses[i].splice(0,0,ts);
sh.appendRow(responses[i]);
}
}
return true;
}
function questionsToHtml(web)
{
var web=(typeof(web)!='undefined')?web:false;
var br='<br />';
var cm=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qnum=cpData.qNum;
var qa=getQAndA();
var qi=getAnswerIndexes();
var s='';
for(var i=0;i<qa.length;i++)
{
//s+='<table>';
//s+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' , qa[i][0],qa[i][1],(qa[i][2])?qa[i][2]:' ',(qa[i][3])?qa[i][3]:' ',(qa[i][4])?qa[i][4]:' ',(qa[i][5])?qa[i][5]:' ');
//s+='</table>';
s+='<div id="d' + qa[i][0] + '" style="font-weight:bold;">' + qa[i][1];
s+='<input type="hidden" value="' + qa[i][0] + '" class="hiding" />';
for(var j=qi.firstIdx;j<=qi.lastIdx;j++)
{
if(qa[i][j])
{
s+=br + '<input type="radio" name="n'+ qa[i][0] +'" value="' + qa[i][j] + '" />' + qa[i][j];
}
}
s+='</div>'
}
s+='<div id="controls">';
s+=br + '<input type="button" value="Submit" onClick="recordData();" />';
//s+=br + '<input type="button" value="Do It Again" onClick="google.script.run.questionsToHtml();" />';
s+='</div>';
s+='</body></html>';
//Logger.log(s);
if(!web)
{
var userInterface=HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(1000).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Current Form')
}
else
{
var output=HtmlService.createHtmlOutputFromFile('htmlToBody').append(s);
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function doGet()
{
return questionsToHtml(true)
}
function getQAndA()
{
var qa=[];
var cma=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qsrcSh=ss.getSheetByName(cpData.qSrc);
var qsrcRg=qsrcSh.getRange(2,1,qsrcSh.getLastRow()-1,qsrcSh.getLastColumn());
var qsrcVa=qsrcRg.getValues();
var qs=selectQuestionIndexes(cpData.qNum,qsrcVa.length-1);
var aIdxs=getAnswerIndexes();
for(var i=0;i<qsrcVa.length;i++)
{
var qas='';
if(qs.indexOf(i)>-1)
{
qas+=qsrcVa[i][0] + cma + qsrcVa[i][1];
for(j=aIdxs.firstIdx;j<=aIdxs.lastIdx;j++)
{
if(qsrcVa[i][j])
{
qas+= cma + qsrcVa[i][j];
}
}
qa.push(qas.split(cma));
}
}
return qa;
}
Here's the htmlToBody.html file
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function recordData()
{
var responses=[];
var cm=',';
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++)
{
var id=divs[i].getAttribute(['id']);
var qnum=$('div#' + id + ' ' + 'input.hiding').val();
var question=document.getElementById(id).innerHTML;
var answer=$('input[name="n' + qnum + '"]:checked').val();
if(id!='controls')
{
if(!answer)
{
window.alert('You did not answer question number ' + Number(i+1) + '. It is a requirement of this survey that all questions must be answered.' );
return;
}
else
{
var end='is near';
var s=qnum + cm + question + cm + answer;
responses.push(s.split(cm));
}
}
}
google.script.run
.withSuccessHandler(displayThanks)
.recordData(responses);
}
function displayThanks()
{
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++)
{
divs[i].style.cssText="display:none;text-align:center";
}
var elemDiv = document.createElement('div');
elemDiv.innerHTML="<br /><h1>Thank You For Your Participation in This Survey</h1>";
document.body.appendChild(elemDiv);
}
console.log('My Code Here');
</script>
<style>
#reply{display:none;}
#collect{display:block;}
body {
background-image: url("");
background-color: #ffffff;
background-repeat: no-repeat;
}
</style>
</head>
<body>

document.getelementbyId in Google Script not working

I am trying to make a google script web app that takes input from an HTML form and passes the input to a script. Right now, the function is failing because document.getelementbyId('text') returns null instead of the actual form value. How can I fix this?
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<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() {
var formObject = document.getElementById('text');
google.script.run.withSuccessHandler(setTable).getSportData(formObject);
console.log(formObject);
}
function setTable(data) {
var div = document.getElementById('output');
div.innerHTML = createTable(data);
}
/**
* Adds an html table
*/
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit()">
<input name="text" type="text" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
Code.gs
//Initalization of global variables for use by the script's custom functions
var ss = SpreadsheetApp.openById("spreadsheetID");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
/**
* Handles HTTP GET requests to the published web app.
* #return {HtmlOutput} The HTML page to be served.
*/
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
/**
* Gets both names and Times of checked-in people from the spreadsheet from the private function getOutput.
* #return {HtmlOutput} A 2D array containing the names and times.
*/
function getSportData(formObject) {
getNamesInSport(formObject);
getTimesInSport(formObject);
var OUTPUT = [
[NAMES],
[TIMES]
];
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
Duplicate of Why does jQuery or a DOM method such as getElementById not find the element?.
You appear to have answered your own question.
document.getElementById('text') returns null because...
You don't have an element with an id="text".
document.getElementById will return null
if an element with the specified ID is not in the document. (Mozilla Developer Network)
The solution, is <input type="text" name="text" id="text">