Whenever I run this code on my webpage, I am unable to get the buttons to perform an event upon being clicked. Nothing happens. I am wanting to display the user input for full name, date of birth and gender into the textbox whenever the user clicks display. If the user clicks next, the current data should be saved to the correct array and when the user clicks clear the current innput in the text boxes and the data in the array should be deleted. What do I need to adjust to make this happen?
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var nameList = new Array();
var dateList = new Array();
var genderList = new Array();
function displayMembers() {
var str = " ";
var listLength = nameList.length;
for(var i = 0; i < listLength; i++) {
document.memberForm.textArea.nameList[i];
document.memberForm.textArea.dateList[i];
document.memberForm.textArea.genderList[i];
}
}
function saveMember() {
nametemp = document.getElementByName("full_name");
nameList.push(nametemp[0].value);
datetemp = document.getElementByName("dob");
dateList.push(datetemp[0].value;
gendertemp = document.getElementByName("gender");
genderList.push(gendertemp[0].value);
}
function clearList() {
nameList= [];
dateList = [];
genderList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" name = "full_name" value = ""/>
Date of Birth: <input type = "text" name ="dob" value = ""/>
<br>
Gender: <input type = "text" name = "gender" value = ""/>
<br>
<textarea name = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick = document.memberForm.
saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick =document.memeberForm.textBox.write.Full Name Date of Birth Gender "displayMembers()">
</button>
</form>
</body>
</html>
There are probably more problems I'm not seeing but here you have an unterminated string.
Change it to
<input type="button" value="NEXT" onclick="document.memberForm.saveMember()"></button>
Related
I have followed a tutorial "Create HTML Form that Moves through RecordSet on Google Sheets" done by Code With Curt.
https://www.youtube.com/watch?v=V9ptq7tZV50&t=152s
The project doesn't look that complicated. It is a simple CRUD app that I want to run in a modal dialog in google sheets, I am a newbie, I really tried to understand the code that I was copying from the video and not make any typos. The form shows up OK from the custom menu but it is not populating with the data from the sheet. The only error I can see is in the console which says "Uncaught ReferenceError: loadRecords is not defined" I have double checked the variable and function names but just can't see the error.
Any help would be appreciated.
Code.gs
function getList()
{
var url = 'https://docs.google.com/spreadsheets/d/1QkSdtybPHA9IrWH2VPw44WtQ9dN_-9KjRVNOuCylMCk/edit#gid=0';
var ss= SpreadsheetApp.openByUrl(url);
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var recordSheet = ss.getSheetByName("WebInscriptions");
var getLastRow = recordSheet.getLastRow();
return recordSheet.getRange(2, 1, getLastRow -1, 9).getValues();
}
function startForm()
{
var form = HtmlService.createHtmlOutputFromFile("Modal");
SpreadsheetApp.getUi().showModalDialog(form, 'Manage New Submissions');
}
function addMenu()
{
var ui = SpreadsheetApp.getUi()
ui.createMenu('HR-Recruitment')
.addItem('New Submissions','startForm')
.addItem('Manage Recruits','startForm')
.addToUi();
}
function onOpen(e)
{
addMenu;
}
Modal.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function loadRecords(record)
{
google.script.run.withSuccessHandler
(function(ar)
{
var record = document.getElementById("record").value;
//console.log (ar);
//console.log (record);
var recordCount = 0;
ar.forEach(function(item, index)
{
if(index == record - 1)
{
document.getElementById("inscriptionDate").value = item[0];
document.getElementById("firstName").value = item[1];
document.getElementById("lastName").value = item[2];
document.getElementById("gender").value = item[3];
document.getElementById("email").value = item[4];
document.getElementById("telNumWhatsApp").value = item[5];
document.getElementById("location").value = item[6];
document.getElementById("visaImageUpload").value = item[7];
document.getElementById("commentMessage").value = item[8];
document.getElementById("referrer").value = item[9];
}
recordCount ++;
});
console.log (recordCount);
document.getElementById("maxRecord").value = recordCount;
}).getList();
}
function NextRecord()
{
var record = document.getElementById("record").value;
var maxRecord = document.getElementById("maxRecord").value;
var nextRecord = Number record + 1;
if(nextRecord <= maxRecord)
{
document.getElementById ("record").value = nextRecord;
loadRecords();
}
}
function PreviousRecord()
{
var record = document.getElementById("record").value;
var previousRecord = Number record - 1;
if(previousRecord >= 1)
{
document.getElementById ("record").value = previousRecord;
loadRecords();
}
}
//loadRecords();
</script>
</head>
<body>
Inscription Date: <input type="text" id="inscriptionDate"/><br>
First Name: <input type="text" id="firstName"/><br>
Last Name: <input type="text" id="lastName"/><br>
Gender: <input type="text" id="gender"/><br>
Email: <input type="text" id="email"/><br>
Telephone Number (WhatsApp): <input type="text" id="telNumWhatsApp"/><br>
Location: <input type="text" id="location"/><br>
VISA Image Upload: <input type="text" id="visaImageUpload"/><br>
Comment or Message: <input type="text" id="commentMessage"/><br>
Referrer: <input type="text" id="referrer"/><br>
<input type="button" value = "PREVIOUS" onclick="PreviousRecord"/>
<input type="text" value="1" id="record" size="2px"/>
<input type="hidden" id="maxRecord"/>
<input type="button" value = "NEXT" onclick="NextRecord"/>
<script>loadRecords();</script>
</body>
</html>
Google Sheet image
Regarding the specific error, the parenthesis are missing in two lines:
var nextRecord = Number record + 1;
var previousRecord = Number record - 1;
Correct syntax
var nextRecord = Number(record) + 1;
var previousRecord = Number(record) - 1;
As mentioned in the Yuri's answer, the video that you used looks to have some problems. From my point of view it's obsolete, one hint is that it's using the now called "Classic Editor" instead of the current default editor. It's weird that the comment with the code was removed, next time start with a more recent example and once you have learned how to debug and learned the differences between the "old" Google Apps Script and the new (i.e. old runtime based on Mozilla Rhino, and the new runtime Chrome V8), go to old tutorials / examples.
P.S. It might be possible that if you are using new editor that your project is using the new runtime, if you want to try the code as is in the video, try enabling the Rhino runtime, for details see https://developers.google.com/apps-script/guides/v8-runtime.
Related
How to go about debugging JavaScript in the HtmlService in Google Scripts
Debugging client side code from Google Apps Script
Given that the youtube guy removed his code and doesn't answer on comments it's obviously that there is something terribly wrong with his code.
As far as I can tell the main problem was that you can't return an array from the function getList() into the HTML form. You need to convert it into a string with return JSON.stringify(array) and then (within HTML form) to convert it back into an array with var array = JSON.parse(array).
Basically, if you add the JSON.stringify and JSON.parse and add the brackets as #Rubén said, it should work.
Just in case, here is my a bit rewritten code:
Modal.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function NextRecord() {
var record = document.getElementById("record").value;
var maxRecord = document.getElementById("maxRecord").value;
var nextRecord = +record + 1;
if(nextRecord <= maxRecord) {
document.getElementById ("record").value = nextRecord;
google.script.run.withSuccessHandler(loadRecords).getList();
}
}
function PreviousRecord() {
var record = document.getElementById("record").value;
var previousRecord = +record - 1;
if(previousRecord >= 1) {
document.getElementById ("record").value = previousRecord;
google.script.run.withSuccessHandler(loadRecords).getList();
}
}
function loadRecords(ar) {
ar = JSON.parse(ar); // <--- here we parse the string back into an array
var record = document.getElementById("record").value;
document.getElementById("maxRecord").value = ar.length;
var item = ar[+record-1];
document.getElementById("inscriptionDate").value = item[0];
document.getElementById("firstName").value = item[1];
document.getElementById("lastName").value = item[2];
document.getElementById("gender").value = item[3];
document.getElementById("email").value = item[4];
document.getElementById("telNumWhatsApp").value = item[5];
document.getElementById("location").value = item[6];
document.getElementById("visaImageUpload").value = item[7];
document.getElementById("commentMessage").value = item[8];
document.getElementById("referrer").value = item[9];
}
google.script.run.withSuccessHandler(loadRecords).getList();
</script>
</head>
<body>
Inscription Date: <input type="text" id="inscriptionDate"/><br>
First Name: <input type="text" id="firstName"/><br>
Last Name: <input type="text" id="lastName"/><br>
Gender: <input type="text" id="gender"/><br>
Email: <input type="text" id="email"/><br>
Telephone Number (WhatsApp): <input type="text" id="telNumWhatsApp"/><br>
Location: <input type="text" id="location"/><br>
VISA Image Upload: <input type="text" id="visaImageUpload"/><br>
Comment or Message: <input type="text" id="commentMessage"/><br>
Referrer: <input type="text" id="referrer"/><br>
<input type="button" value = "PREVIOUS" onClick="PreviousRecord()"/> // <-- don't forget the brackets here
<input type="text" value = "1" id = "record" size = "2px"/>
<input type="hidden" value = "" id = "maxRecord"/>
<input type="button" value = "NEXT" onClick="NextRecord()"/> // <-- don't forget the brackets here
</body>
</html>
Code.gs
function getList(){
var url = 'https://docs.google.com/spreadsheets/d/1QkSdtybPHA9IrWH2VPw44WtQ9dN_-9KjRVNOuCylMCk/edit#gid=0';
var ss= SpreadsheetApp.openByUrl(url);
// var ss = SpreadsheetApp.getActiveSpreadsheet();
var recordSheet = ss.getSheetByName("WebInscriptions");
var lastRow = recordSheet.getLastRow();
var list = recordSheet.getRange(2, 1, lastRow-1, 10).getValues();
return JSON.stringify(list); // <--- here we return a string instead of the array
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile("Modal.html");
SpreadsheetApp.getUi().showModalDialog(form, 'Manage New Submissions');
}
function addMenu() {
var ui = SpreadsheetApp.getUi()
ui.createMenu('HR-Recruitment')
.addItem('New Submissions','startForm')
.addItem('Manage Recruits','startForm')
.addToUi();
}
function onOpen(e) { addMenu() }
i want to transfer the input value from these textbox to another web page textbox in html
there are two files
this is the first web page
javscript code
function to transfer file to another web page
function transferdata() {
var inputTest = document.getElementById('FROM').value;
var inputTest1 = document.getElementById('TO').value;
var inputTest2 = document.getElementById('jdate').value;
if (inputTest=="") {
window.open('report_pengambilan_singgle.html','','height=650,width=1200');
}
else {
window.open('trial25.html?name=' + inputTest,'','height=650,width=1200');
}
}
html code
this is the body of the code
<form >
<label ><H2>SOURCE</h2></label><br>
<input type="text" id="FROM" name="FROM" ><BR>
<label ><H2>DESTINATION</H2></label><BR>
<input type="text" id="TO" name="TO" ><BR>
<h2> Date of Journey<input type = "date" name = "jdate" id = "jdate"></h2>
<br>
</form>
second file this the another file which will recive the data
javscript code
// Recive data from destination.html
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById("source1").value = data.name;
document.getElementById("date").value = data.name;
document.getElementById("dest").value = data.name;
}
html code
this is the body of the another web page code
<form>
<h3> Source <input type = "text" name = "source1" id = "source1" /> </h3>
<h3> Destination <input type = "text" name = "dest" id = "dest" /> </h3>
<h3> Booking Date <input type = "date" name = "date1" id = "date1" /> </h3>
</form>
this the input field in which i want to recive data from first web page input field
I was working on some code where I create a website to practice French. I created a method to check my answers but it did not work for a second question. My HTML and JavaScript are below:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src = "Contest.js"></script>
<title>Verb Practice</title>
</head>
<body>
<input type = "button" onclick = "location.href = 'file:///C:/Users/aryan/Desktop/HTML,%20JavaScript,%20&%20CSS/Contest.html#vocab';" value = "Back To Main" />
<center>
<h2>Verb Practice</h2>
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type = "text" name = "Q1" value = "" id = "ansGiven"><br>
<input type = "submit" value = "Answer" id = "Q1" onclick = "getAns('acheter')">
<p id = "ansRes"></p>
</fieldset>
<fieldset>
<p>What does the verb <i>attendre</i> mean?</p>
<input type = "text" name = "Q2" value = "" id = "ansGiven"><br>
<input type = "submit" value = "Answer" id = "Q2" onclick = "getAns('to wait')">
<p id = "ansRes"></p>
</fieldset>
</center>
</body>
</html>
JavaScript:
function getAns(ans) {
var ansGiven = document.getElementById("ansGiven").value;
console.log(ans);
console.log(ansGiven);
if (ansGiven === ans) {
document.getElementById("ansRes").innerHTML = "Correct!";
} else {
document.getElementById("ansRes").innerHTML = "Try Again.";
}
ansGiven = "";
}
Theoretically, the method getAns() should say whether the input for the given question is correct or wrong. Instead, the first question works fine, but the second question displays its input as nothing. Why would this be happening and what was wrong with the code?
From w3schools:
An ID should be unique within a page. However, if more than one
element with the specified ID exists, the getElementById() method
returns the first element in the source code.
To fix that you have to distinguish between your multiple ansGiven and ansRes too (eg. ansGiven1, ansGiven2, ...). This will lead to more complicated code and you will probably have to think about it for a while. You can also use the click event target to find out which element has been clicked.
This happens because you have non-unique IDs for some of the DOM elements and the document.getElementById() function returns the first element with the given ID.
ansGiven and ansRes are used two times each. Instead, use unique IDs like ansGiven-1, ansGiven-2, etc. and ansRes-1, ansRes-2 etc.
You can change the function signature to accept the number of the question as argument:
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type="text" name="Q1" value="" id="ansGiven-1"><br>
<input type="submit" value="Answer" id="Q1" onclick="getAns('acheter', 1)">
<p id="ansRes-1"></p>
</fieldset>
function getAns(ans, answerNumber) {
var ansGiven = document.getElementById("ansGiven-" + answerNumber).value;
if (ansGiven === ans) {
document.getElementById("ansRes-" + answerNumber).innerHTML = "Correct!";
} else {
document.getElementById("ansRes-" + answerNumber).innerHTML = "Try Again.";
}
ansGiven = "";
}
"id" of dom elements must be unique. Your inputs have the same id "ansGiven" and result paragraphs "ansRes". First of all, you have to make them unique. Absolutely not the best method, but since you said you're practicing, give the below code a shot:
<!DOCTYPE html>
<html>
<head>
<script src = "Contest.js"></script>
<title>Verb Practice</title>
</head>
<body>
<input type = "button" onclick = "location.href = 'file:///C:/Users/aryan/Desktop/HTML,%20JavaScript,%20&%20CSS/Contest.html#vocab';" value = "Back To Main" />
<center>
<h2>Verb Practice</h2>
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type = "text" name = "Q1" value = "" id = "ansGiven1"><br>
<input type = "submit" value = "Answer" id = "Q1" onclick = "getAns('acheter', 1)">
<p id = "ansRes1"></p>
</fieldset>
<fieldset>
<p>What does the verb <i>attendre</i> mean?</p>
<input type = "text" name = "Q2" value = "" id = "ansGiven2"><br>
<input type = "submit" value = "Answer" id = "Q2" onclick = "getAns('to wait', 2)">
<p id = "ansRes2"></p>
</fieldset>
</center>
</body>
</html>
javascript
function getAns(ans, questionIndex) {
var ansGiven = document.getElementById("ansGiven" + questionIndex).value;
console.log(ans );
console.log(ansGiven);
if (ansGiven === ans) {
document.getElementById("ansRes" + questionIndex).innerHTML = "Correct!";
} else {
document.getElementById("ansRes" + questionIndex).innerHTML = "Try Again.";
}
ansGiven = "";
}
I am trying to create an array from user input in JavaScript and display the latest array as the numbers are appended to the array. The numbers are not getting printed.
Kindly help.
HTML part :
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<form id = "arrays" method = "" onsubmit="arrAppend(document.getElementById('num').value);">
<input type ="submit" value="Append" />
</form>
JavaScript part :
<script>
var myarr = [];
function arrAppend(num) {
myarr.push(+num);
text = "";
for (var x = 0; x< myarr.length; x++) {
text += myarr[x];
}
console.log(text);
}
</script>
This is working :
HTML :
<input type = "text"
id = "addNumber" />
<input type = "button"
id = "addToArray"
value = "Append"
onclick = "arrAppend();" />
JavaScript :
function arrAppend() {
myarr[x] = document.getElementById('addNumber').value;
alert("Element : "+myarr[x]+" is added at index "+x);
x++;
document.getElementById('addNumber').value = "";
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<input type ="submit" value="Append" onclick="arrAppend(document.getElementById('num').value);"/>
why do you need a form? are you submitting something to the server? when you submit a form it will clear the global array as well.
I need to display the answer from the form in a story. The story must be displayed below the form only after the form is successfully submitted (not an alert), and with the form remaining on the page (not a new page). I am able to insert the form values into the story, but need help with displaying the story after form is submitted. I cannot use anything but html and javascript. I think this can be done with innerHTML.
<head><title>Questions</title>
<script type = "text/javascript" src="quiz1.js">
</script>
</head><body>
<h1>Tell Me About Yourself</h1>
<form name = "the_form" action = "" method = "post"
onSubmit = "var the_result = checkMandatory(); return the_result;">
Full Name:<input type = "text" name = "name" id = "name" /><br/>
Favourite Animal:<input type = "text" name = "animal" id = "animal"><br/>
Favourite Food:<input type = "text" name = "favFood" id = "favFood"><br/>
Favourite Destination:<input type = "text" name = "destination" id = "desitnation"><br/>
Least Favourite Food:<input type = "text" name = "leastFav" id = "leastFav"><br/>
Happiest Moment:<input type = "text" name = "moment" id = "moment"><br/>
Adjective that describes you:<input type = "text" name = "adjective" id = "adjective"><br/>
<br>
<input type="button" value="Submit" onClick = "checkMandatory(); return false;"/><br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>
function checkMandatory()
{
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0))
{
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0,name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
document.write("The young person's name was "+firstName+". "+firstName+" loved to ride
"+animal+
" almost every day. "+firstName+"'s second happiest moment, only next to "+moment+", was in
"+destination+", where "+favFood+
" was served for breakfast, lunch and dinner. It was only when "+firstName+" was told that
"+favFood+
" is actually made from "+animal+", that it instantly became "+firstName+"'s least
favourite food, even worse than "+leastFav+
", and that made "+firstName+" feel very "+adjective+" indeed.")
//document.getElementById('storyDiv').innerHTML = document.getElementById('name').value;
//document.getElementById(‘storyDiv’).innerHTML="The boy's name was "+firstName;
//document.write(‘storyDiv’).innerHTML="The boy's name was " + firstName;
}
}
You can achieve this by posting your form using ajax.
Don't call writethetext(); in your submit button
I'll use jQuery in my solution:
$(function() {
$("form").on("submit", function(e) {
var data = JSON.stringify($("form").serializeArray());
e.preventDefault();
$.post("yourserver/path/", data, function(result) {
writethetext(result);
});
});
});
function checkMandatory() {
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0)) {
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0, name.indexOf(" "));
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
}
}
function writethetext() {
document.getElementById(‘storyDiv’).innerHTML =
("There once was a boy named" + name;)
var firstName = name.substring(0, name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
}
function writethetext(text) {
document.getElementById(‘storyDiv’).innerHTML = text;
}
}
<html>
<head>
<title>Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="quiz1.js">
</script>
</head>
<body>
<h1>Tell Me About Yourself</h1>
<form name="the_form" action="" method="post" onSubmit="var the_result = checkMandatory(); return the_result;">
Full Name:
<input type="text" name="name" id="name" />
<br/>Favourite Animal:
<input type="text" name="animal" id="animal">
<br/>Favourite Food:
<input type="text" name="favFood" id="favFood">
<br/>Favourite Destination:
<input type="text" name="destination" id="desitnation">
<br/>Least Favourite Food:
<input type="text" name="leastFav" id="leastFav">
<br/>Happiest Moment:
<input type="text" name="moment" id="moment">
<br/>Adjective that describes you:
<input type="text" name="adjective" id="adjective">
<br/>
<br>
<input type="button" value="Submit" onClick="checkMandatory();
return false;" />
<br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>