Why the program not run correctly? - html

I am beginner to html and asp. I should write code of the program in Notepad. I want the program that when I click on the Random Button, generate a random number and when I click on the Check button, the program compare between my guess and random number. I write this code but when run the program, not show random number and not compare. Why?
<html>
<head>
<script>
var numOfGuess=new number(0);
var numRandom;
var num;
function RandomNum(){
numRandom=new number(math.floor(math.random()*100));
response.write(numRandom);
numOfGuess=0;
}
fucntion Guess(){
num=document.getElementById("guess");
var alert="";
if(num.value<numRand){
alert="grater than!";
numOfGuess++;
}
esle if (num.value>numRand){
alert="lower than!";]
numOfGuess++;
}
else{
alert="equal!";
numOfGuess++;
}
document.getElementById("message").innerHtml=alert;
}
</script>
</head>
<body>
<input type="text" id="guess">
<input type="submit" onClick='RandomNum()' value="Random">
<p id="message"></p>
<input type="submit" onClick='Guess()' value="Check">
</body>
</html>

Like AnthonyLeGovic said:
you need to be rigorous when programming
here is what you are looking for:
<html>
<head>
<title>test</title>
<script language="javascript">
var numRand = 0;
var numGuess = 0;
var numTry = 1;
function setRand(){
numRand = Math.floor((Math.random()*100)+1);
numTry = 0;
alert("done");
}
function guess(){
var msg = document.getElementById("message");
numGuess=Number(document.getElementById("guess").value);
if(numGuess>numRand){
msg.innerHTML = "lower than!";
}
else if(numGuess<numRand){
msg.innerHTML = "grater than!";
}
else {
msg.innerHTML = "equal! tried " + numTry +"times";
}
numTry++;
}
</script>
</head>
<body>
<input type="text" id="guess" />
<input type="button" onclick="setRand()" value="Random" />
<p id="message"></p>
<input type="button" onclick="guess()" value="Check" />
</body>
do not forget language="javascript" in your script tag else your script will not work!

You need to be rigorous when programming.
There are some syntax errors in your code like :
fucntion instead of function while declaring Guess function.
you declare numRandom as a global variable but you are using numRand then, unfortunately these two variables are not the same at all. Moreover numRand isn't declare (which is logic because it should be numRandom).
you are using innerHtml instead of innerHTML (case sensitive) in order to help the user to find the right number.
Maybe there are some more mistakes I've forgotten right there.

Related

Trying to validate input on sidebar against field on a spreadsheet using withFailureHandler

I am trying to validate user input against field on spreadsheet. Not sure if I am using withFailureHandler correctly. I have an output field defined in the form and this would show 'duplicate entry' if the entry is already present on the spreadsheet. I tried the following code for just testing to see if the form will display any output and this does not seem to be working.
code.gs
function sendItem() {
var form = HtmlService.createHtmlOutputFromFile('test');
SpreadsheetApp.getUi().showSidebar(form);
}
function getTest(sometext) {
return false;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<input type="text" id="amount" name="amount" placeholder="serving in gms"><br>
<button class="myStyle" onclick="sendTest()">&#129746</button>
</div>
<div id="output" placeholder=" any errors will appear here"></div>
</body>
</html>
<script>
function sendTest(){
var amount = document.getElementById("amount").value;
google.script.run.getTest(amount)
.withFailureHandler(onFailTest);
document.getElementById("amount").value = "";
}
function onFailTest() {
var output = document.getElementById("output");
text = "duplicate entry retry";
output.innerHTML = text;
}
</script>
I'd do the html like this:
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<input type="text" id="amount" name="amount" placeholder="serving in gms"><br>
<button class="myStyle" onclick="sendTest()">&#129746</button>
</div>
<div id="output"></div>
<script>
function sendTest(){
var amount = document.getElementById("amount").value;
google.script.run
.withFailureHandler(function(){output.innerHTML = "duplicate entry retry";})
.getTest(amount);
document.getElementById("amount").value = "";
}
</script>
</body>
</html>
But I'd use withSuccessHandler to handle the getTest return onFailureHandler will handle errors not false returns, I think.

Sending input from HTML using callback

I have the code for the input from a user, and I have the callback, I am just confused on how to have the data sent using the callback
my code:
HTML
<!DOCTYPE html>
<html>
<head>
<base target="\_top">
</head>
<body>
<label>User info: </label>
<div align="justify">
<input type= "text" id = "email">
</div>
<br>
<button id="searchData"> Search data sheet </button>
<script>
//Above creates a box for user input [//document.getElementById](//document.getElementById)("searchData").addEventListener("click",addHeaders); document.getElementById("searchData").addEventListener("click",google.script.run.withSuccessHandler(onSuccess).testCase());
//gets the button1 element and listens for a click then runs the function addName.
function onSuccess(numUnread) {
var div = document.getElementById('output');
div.innerHTML = numUnread
} ​
google.script.run.withSuccessHandler(onSuccess).testCase()
</script>
</body>
</html>
Apps Script
function doGet() {
return HtmlService.createHtmlOutputFromFile('frontEnd');
}
function testCase(input)
{
Logger.log((input + ' hello'))
return (input + ' hello')
}
My expected would be the input + " hello", instead I got "undefined hello"
Let's say that in your html you have a button like this with a div above it:
<body>
<div id="message"></div>
<input type="button" value="Hello" onClick="sayHello();" />
<script>
//When you click the button this function gets called
function sayHello() {
google.script.run
.withSuccessHandler(function(msg){
document.getElementById("message").innerHTML=msg;//message will appear in the div
})
.sayHelloToServer();//This function is on the server
console.log('My Code');
</script>
</body>
Then in Code.gs:
function sayHelloToServer() {
return "Hello. We're very happy that you came to visit us.";//this is returned to withSuccessHandler(function(msg){}) or you can also use a standalone function in which you simply put its name in like this .withSuccessHandler(funcname)
}
This is explained in Client to Server Communication

Uploading An Image With Google Apps Script To A GSheet - Passing Values To And From HTML Service Modal Dialog

I'm trying to trigger a file upload off of a Google Sheet, taking the uploaded file, add it to a Google Drive folder, and then return the URL of the uploaded file and place it in a cell on the Sheet. I'm currently triggering the file upload by using a checkbox. Once you set the checkbox to TRUE, it'll pop up a dialog box with a file upload input field. This is triggered by an installed onEdit function. Also, info on the row in the sheet will be used to name the newly uploaded file. This info will be input manually on the sheet.
I get to the showModalDialog line, and the dialog box comes up just fine, but I can't figure out how to pass variables from the original function to the HTML service and then back again (with the file) to upload to Drive, set the name, and put the URL back on the sheet.
Here's the first function in Code.gs, receiving values from the onEdit function:
function addFile(ss,ui,row,total) { \\Triggered if edited cell is in column 25 & value is TRUE
Logger.log('add file function');
var name = ss.getRange(row,1).getDisplayValue();
var date = ss.getRange(row,3).getDisplayValue();
var filename = 'Row ' + row + ' - ' + name + ' - ' + date + ' - ' + total;
var htmlTemp = HtmlService.createTemplateFromFile('Index');
htmlTemp.fName = filename;
htmlTemp.position = row;
var html = htmlTemp.evaluate().setHeight(76).setWidth(415);
ui.showModalDialog(html, 'Upload');
Logger.log('end of add file function');
}
And here's what's in Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form>
Please upload image below.<br /><br />
<input type="file" name="upload" id="file" accept="image/*,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
function formData(obj){
var newFileName = <? fName ?>;
var rowNum = <? position ?>;
google.script.run.withSuccessHandler(closeIt).upload(obj,newFileName,rowNum);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
And here's the return function on Code.gs:
function upload(obj,newFileName,rowNum) {
Logger.log('upload function');
var upFile = DriveApp.getFolderById('[folderid]').createFile(obj).setName(newFileName);
var fileUrl = upFile.getUrl();
Logger.log(fileUrl);
var urlCell = SpreadsheetApp.getSheetByName('sheet name').getRange(rowNum,26);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
Running this code, the dialog box comes up just fine, and I'm able to select a file for upload. However, clicking the Submit button does nothing, and the box stays up until I X it out or hit the Cancel button. The logs only get so far as 'end of add file function' and never gets to the upload function. Should the google.script.run.withSuccessHandler line close the dialog box, or is something else needed to confirm / get the file and close the box?
I've been searching online and have found a number of posts relating to this, but none seem to address this specific issue. This is also pretty much a frankenstein of code I've cobbled together from those posts, so it's possible there's just something that doesn't belong in there and if that is the case I do apologize. Any help would be appreciated; thanks!
[Edit: the submit button wasn't opening a separate tab because I was using <input type="button"> instead of <button>.]
According to the documentation [1] in the “Parameters and return values” part,
if you’re going to send the form object as a parameter “it must be the function’s only parameter”. So you should send the parameters inside the form, using inputs of types “hidden” or “text”, then, from code.gs you can retrieve the input data of the Form object.
Another thing stated in the documentation [1] in the “form” section, is that you need to disable the default submit action with preventFormSubmit function.
Another problem is that the correct way of printing the variables passed to the template are using <?= ?> instead of <? ?> which works to execute code but not to print variables. [2]
Your “addFile” function is all right. Below is the code i've tested on my environment and I was able to upload an image successfully and print the url in the sheet.
Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
Please upload image below.<br /><br />
<input type="hidden" name="fname" id="fname" value="<?= fName ?>"/>
<input type="hidden" name="position" id="position" value="<?= position ?>"/>
<input type="file" name="file" id="file" accept="image/jpeg,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
//Disable the default submit action using “func1”
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function formData(obj){
google.script.run.withSuccessHandler(closeIt).upload(obj);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
Code.gs (upload function):
function upload(obj) {
//Retrieve the input data of the Form object.
var newFileName = obj.fname;
var rowNum = obj.position;
var blob = obj.file;
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum,5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
[1] https://developers.google.com/apps-script/guides/html/communication
[2] https://developers.google.com/apps-script/guides/html/templates

Modifying an existing Calendar Event from HtmlService input

I'm trying to add a "Sign Up" link to a Google Calendar Event where upon clicking the user is prompted via HtmlService to submit their email address. Their email address is then added to the event.
Here's a similar example. What I'd like to do differently is use HtmlService to have the user input their email address, which then is passed back to GAS to be added to the Calendar Event in question. That way they can choose the email they want (instead of whatever Session.getActiveUser().getEmail() returns) to sign up with. (and by sign up, I mean get added to the guest list - they still have to accept the invite, but that's fine).
Is this possible? I'm not seeing any examples of this so maybe there's a better way?
I am starting to tear out what little hair I have. I've included my latest sample code, where I pass the event object into the HTML template. It's not throwing an error, but it's not working either. Thank you in advance!!
Code.gs:
function doGet(event) {
// // shorten the event parameter path;
var param = event.parameter;
// // get the calendar event id passed in the query parameter
var eventId = param.eId;
var calId = param.calId;
var cal = CalendarApp.getCalendarById(calId);
var t = HtmlService.createTemplateFromFile('Index');
t.eObj = cal.getEventById(eventId);
return t.evaluate();
}
function addEmail(emObj,myForm){
var guestEmail = myForm.user;
emObj.addGuest(guestEmail)
}
and Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function update() {
alert("Success!");
}
</script>
</head>
<body>
<form id="myForm">
<input id="userEmail" name="user" type="text" />
<input type="button" value="Submit" onClick="google.script.run.withSuccessHandler(update).addEmail(eObj,this.form)" />
</form>
</body>
</html>
You don't have scriptlets in your html file, so you don't need to evaluate a template. I've added another 2 input fields for the calId and eventId. They get replaced in the HTML before being served. Then the event ID and Cal ID are passed back in the form object.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function update() {
alert("Success!");
}
</script>
</head>
<body>
<form id="myForm">
<input id="userEmail" name="user" type="text" />
<input name="calId" type="text" style="display:none"
value="zzz_calID_zzz"/>
<input name="eventId" type="text" style="display:none"
value="zzz_eventID_zzz"/>
<input type="button" value="Submit" onClick="google.script.run
.withSuccessHandler(update)
.addEmail(this.form)" />
</form>
</body>
</html>
doGet:
function doGet(event) {
// // shorten the event parameter path;
var param = event.parameter;
// // get the calendar event id passed in the query parameter
var eventId = param.eId;
var calId = param.calId;
var t = HtmlService.createHtmlOutputFromFile('Index').getContent();
t = t.replace('zzz_calID_zzz',calId);
t = t.replace('zzz_eventID_zzz',eventID);
return HtmlService.createHtmlOutput(t);
}
Server code:
function addEmail(myForm){
var cal = CalendarApp.getCalendarById(myForm.calId);
var event = cal.getEventById(myForm.eventId);
var guestEmail = myForm.user;
event.addGuest(guestEmail)
}

Find Next in Google Apps

We have a bunch of documents we would like to convert to Google Docs. In MSWord we have a macro where our users hit a key command and it will automatically find a string of characters (%%%) and then select them. So we can quickly go in and replace all occurrences of them with the correct data.
I am unable to find anything in Google Docs or scripts that can do that.
TL;DR
I need to write a script that will find and select text so we can quickly write over it. Any help or thoughts?
This function works in conjunction with a sidebar to find and select text.
function findTextAndSelect(s){
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var rgel=body.findText(s);
if(rgel){
var rgbldr=doc.newRange();
rgbldr.addElement(rgel.getElement(),rgel.getStartOffset(),rgel.getEndOffsetInclusive());
var rg=rgbldr.build();
if(rg.getRangeElements().length>0){
doc.setSelection(rgbldr.build());
return 'found';
}
else{
return 'Not Found';
}
}else{
return 'Not Found';
}
}
**This is the sidebar code. **
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function findAndSelect(){
$('#status').html('');
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(function(hl){
$('#status').html('<strong>Status:</strong>' + hl);
})
.findTextAndSelect(txt);
}
console.log("My code");
</script>
</head>
<body>
<br />Text:<br /><textarea id="txt1" rows="6" cols="35"></textarea>
<br /><input type="button" id="btn3" value="Find Text and Select" onClick="findAndSelect();" />
<div id="status"></div>
</body>
</html>
You need to add the code to load the sidebar and possibly put it into the menu.