Uncaught SyntaxError: Unexpected identifier at compute - javascript

I have some code that returns an Uncaught SyntaxError when I run it but I don't understand why.
I tried putting it through JSHint but to no avail.
Here is the code that is apparently wrong:
function compute(expr, x, string) {
var whatisx = "x=" + toString(x) + ",";
var tempAns = parseFloat(eval(whatisx + expr));
var roundedAnswer = roundNumber(tempAns, 3);
if (isNaN(tempAns) === true) {
alert("error");
}
if (string) {
return toString(roundedAnswer);
} else if (!string) {
return roundedAnswer;
} else {
return null;
console.log("Error trying to compute value. The string value must be boolean.");
}
}
When I run it, I don't get any console logs and it says there is an error at the plus sign in:
var tempAns = parseFloat(eval(whatisx + expr));
Another problem in the same program that is also a SyntaxError is in my HTML.
Here is my html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Grapher</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js" charset="utf-8"></script>
<script type="text/javascript" src="functions.js" charset="utf-8"></script>
<script type="text/javascript" src="sketch.js" charset="utf-8"></script>
</head>
<body>
<form>
<label>Graph y=</label>
<input id="mathExpr" type="text" name="mathExpr" value="">
<label> from x=</label>
<input id="x_min" type="text" name="x_min" value="">
<label> to </label>
<input id="x_max" type="text" name="x_max" value="">
<input type="button" name="result" value="Result" onclick="compute(); runp5();">
</form>
<h2>Answer: <span id="output"></span></h2>
</body>
</html>
For this one, it says there is an error at
<input type="button" name="result" value="Result" onclick="compute(); runp5();">
What can I do to fix both of those?
Thanks in advance.
Edit: Question resolved. I was calling compute without any parameters. (thanks #Pointy)

I came back to this question just now, and I realized I was making another mistake. Here is my fix:
As user Pointy noticed, I was calling compute() without its required parameters.
I should add console.log() in my else statement before the return otherwise it won't get called at all:
// ...
else {
console.log('message'); // this should come before return
return null;
}
This doesn't actually fix the problem I detailed, but I wanted to point it out for any future readers.

Related

I cannot get input to work under google app script

I'm writing a web app under google sheets and can't get an input field to work. What am I doing wrong?
everything works but uname is always empty (not undefined).
edit: I'm adding the full code after simplifying it as much as I could.
In the log I get "name" regardless of the input I type in.
In the file code.gs:
function doGet () {
var participant = {};
var templ = HtmlService.createTemplateFromFile('out');
return templ.evaluate();;
}
function formSubmit(name) {
Logger.log("name " + name);
}
In out.html
<!DOCTYPE html>
<html>
<head>
<base target ="_top">
</head>
<body dir="rtl"; background-color: #92a8d1;>
<label> Name 1 </label> <input type="text" id="firstname"><br>
<label> Name 2 </label> <input type="text" id="lastname"> <br><br>
<button type="button" id="send">Send</button>
<script>
document.getElementById("send").addEventListener("click", getData());
function getData(){
var uname = document.getElementById("firstname").value;
google.script.run.formSubmit(uname);
}
</script>
</body>
</html>
You want to retrieve the value of <input type="text" id="firstname"> when the button is clicked.
In your current situation, when you see the log with the script editor, only name is retrieved. This is your current issue.
You want to know the reason of the issue.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your script, document.getElementById("send").addEventListener("click", getData()); is used. In this case, when the HTML is loaded, getData() is run by () of getData(). By this, uname becomes "" and "" is sent to formSubmit(uname), then, when you see the log, you see name. And also, in this case, even when the button is clicked, google.script.run.formSubmit(uname); cannot be run. I think that this is the reason of the issue of your script in your question.
In order to avoid this, please modify your script as follows.
Modified script:
From:
document.getElementById("send").addEventListener("click", getData());
To:
document.getElementById("send").addEventListener("click", getData);
By the above modification for your script, when sample is inputted to "Name 1" and click "Send" button, you can see name sample at the log with the script editor.
Reference:
addEventListener()
If I misunderstood your question and this was not the result you want, I apologize.
Here's an example form that you can probably use to accomplish your needs. This form is used as a simple receipt collection system. You can actually take and upload images from a mobile device with it. I also has text and button input types and upload a form node.
Code.gs
var receiptImageFolderId='';
var SSID='';
function onOpen() {
SpreadsheetApp.getUi().createMenu('Receipt Collection')
.addItem('Run as Dialog', 'showAsDialog')
.addItem('Run as Sidebar', 'showAsSidebar')
.addToUi();
var sh=SpreadsheetApp.getActive().getSheetByName("Sheet1");
sh.getRange(sh.getLastRow()+1,1).activate();
}
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Sheet1').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function doGet() {
var output=HtmlService.createHtmlOutputFromFile('receipts').setTitle('thehtml');
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}
function showAsDialog() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Receipts')
}
function showAsSidebar() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showSidebar(ui);
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd")
return {date:datestring};
}
The Html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
Here's what the dialog looks like:

javascript on change using while loop

Error:
TypeError: d.options is undefined while(i<=d.options.length){
Hi i have this javascript of mine which has the select option to choose from. and from choosing from the select options it will display to the textbox field im using this onchange and using it while loop. can someone help me how to figure this out?? using while loop code?
Here's my code below
<!DOCTYPE html>
<html>
<head>
<title>Activity 2 while loop</title>
<script type="text/javascript">
function tellMe(d){
var i = 0;
while(i<=d.options.length){
if(d.listbox1.options[i].selected == true){
d.choose.value = d.listbox1.options[i].text;
}
}
}
</script>
</head>
<body>
<form name="form1">
<p>Girl's qualities you want?</p>
<select name="listbox1" size="5" onchange="tellMe(this.form)">
<option>Pretty</option>
<option>Sexy</option>
<option>Hot</option>
<option>Intelligent</option>
<option>Funny</option>
</select>
<br />
<p>
You Choose: <input type="text" name="choose" />
</p>
</form>
</body>
</html>
any help is muchly appreciated! thanks
Fiddle
Fixed it:
<!DOCTYPE html>
<html>
<head>
<title>Activity 2 while loop</title>
<script type="text/javascript">
function tellMe(d){
document.getElementById("choose").value = d.value;
}
</script>
</head>
<body>
<form name="form1">
<p>Girl's qualities you want?</p>
<select name="listbox1" size="5" onchange="tellMe(this)">
<option>Pretty</option>
<option>Sexy</option>
<option>Hot</option>
<option>Intelligent</option>
<option>Funny</option>
</select>
<br />
<p>
You Choose: <input type="text" id="choose" name="choose" />
</p>
</form>
</body>
</html>
You were trying to get this.form but it should have been this, then the value of this (this.value).
Then, all you had to do was set the input type with name='choose', however I gave it an ID of choose to make it easier to select, then gave that value d.value, which was the value of listbox1.
You are passing the form element, which doesn't have options. Change d.options to d.listbox1.options
while(i<=d.listbox1.options.length){
After that is fixed your second problem will become apparant, whch is that you fail to increment i:
while(i<=d.listbox1.options.length){
...
i++;
}
You aren't incrementing i. You need to add i++ at the end of your while loop. You also need to target listbox1 in your while loop.
function tellMe(d){
var i = 0;
while(i<=d.listbox1.options.length){ // <-- use d.listbox1.options.length
if(d.listbox1.options[i].selected == true){
d.choose.value = d.listbox1.options[i].text;
}
i++; // <-- add increment here
}
}

How to validate a form's input value

I am trying to validate a form's input value after clicking a button using jQuery and javascript.
Right now, if I put in a value for the input and click submit the input field and button just disappears. Any idea what I have wrong here?
The HTML file...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
<input type="text" id='input_1'>
<input type="submit" value="Send" id="send">
</form>
</body>
</html>
The script file...
$(document).ready(function() {
$('.send').click(function() {
validateInput(document.getElementById('#input_1'));
function validateInput(inputValue){
if (inputValue === 3) {
alert("Element cannot be equal to 3");
}
}
});
});
$(document).ready(function() {
$('#send').live('click',function() { //Because send is the id of your button
if(validateInput(document.getElementById('#input_1'))){
alert("Element cannot be equal to 3");
return false;
}
else{
//Do something else
}
function validateInput(inputValue){
if (inputValue == 3) {
return false;//Will prevent further actions
}
}
});
});
this $('.send').click(function() {
should be $("#send").click(function() {.
Notice the Hash symbol and not the dot (.), dot is used if the selector is a class whereas the # is used if the selector is an ID.
2.You should move the validation function outside the $(document).ready(function().. Hope that helps
Thank you all for your responses. Unfortunately, I wasn't able to get it to work using your recommendations. I decided to use jQuery to get the element and appended a message to a div instead of using alert. This was a different approach but ended up working.
HTML...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
<input type="text" name="input"/>
</form>
<button id="send">Send</button>
<div class="error">
</div>
</body>
</html>
SCRIPT...
$(document).ready(function() {
$('#send').click(function(){
var toValidate = $('input[name=input]').val();
if (toValidate == 3) {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is invalid" + '</div>');
}
else {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is valid" + '</div>');
}
});
});

JavaScript Filling Default value back into text field on blur

I have a problem. I want the text to be filled by the default value when user lefts it blank here is my code. Please help me to tackle this error.
<html>
<head>
<title>
</title>
<script lang='javascript'>
function makeBlank(obj,defMsg){
if(obj.value==defMsg){
obj.value="";
}
}
function fillDefValue(obj,defMsg){
if(obj.value==""){
obj.value=defMsg;
}
}
</script>
</head>
<body>
<input style="width:190px" onblur="fillDefValue(this,'User Name')" onfocus="makeBlank(this,'User Name')" value="Name" name="fromname" id="fromname" type="text">
</body>
</html>
You don't have to pass the default value to the functions, it's integral part of the textbox element itself:
function makeBlank(obj) {
if(obj.value === obj.defaultValue){
obj.value = "";
}
}
function fillDefValue(obj) {
if(obj.value == "") {
obj.value = obj.defaultValue;
}
}
Then pass only the element:
onblur="fillDefValue(this);" onfocus="makeBlank(this);"
Live test case - it works on all major browsers, probably all browsers.
Your code has a minor error. The functions which make the text field blank or filled with default value have an if statement which checks the condition if(obj.value==defMsg) which is defMsg='User Name'. But in the text field you are assigning value = "Name" so the if condition never become true. Thats why your code is not working. You should either use <input .... value="User Name" ......> or you can call the both functions as <input ...onblur="fillDefValue(this,'Name')" onfocus="makeBlank(this,'Name')" vlaue="Name"....>. Doing any of these two changes the code will work fine. Here is your code with the first change I mentioned:
<html>
<head>
<title>
</title>
<script lang='javascript'>
function makeBlank(obj,defMsg){
if(obj.value==defMsg){
obj.value="";
}
}
function fillDefValue(obj,defMsg){
if(obj.value==""){
obj.value=defMsg;
}
}
</script>
</head>
<body>
<input style="width:190px" onblur="fillDefValue(this,'User Name')" onfocus="makeBlank(this,'User Name')" value="User Name" name="fromname" id="fromname" type="text">
</body>
</html>
You’re probably looking for the placeholder HTML attribute.
<input placeholder="e.g. username42">
You only need JavaScript as a fallback for older browsers. This jQuery plugin will take care of it for you. Here’s a demo: http://mathiasbynens.be/demo/placeholder

Disable the text boxes

I am beginner to html. I have two text boxes say t1 and t2 If t1 is filled with some data then then other text box t2 should be disable. Please let me know hot to do it. Thanks in advance
Based on your simple scenario description, here's an implementation that works cross-browser and without any third-party javascript library:
<html>
<head>
<script type="text/javascript">
window.onload = function(){
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
t1.onchange = function(){
t2.disabled = t1.value.length > 0;
}
}
</script>
</head>
<body>
<form>
t1:<input type="text" id="t1" name="t1" /><br/>
t2:<input type="text" id="t2" name="t2" />
</form>
</body>
</html>
<head>
<script type="text/javascript">
function verify(){
var t1 = document.getElementById ('first');
var t2 = document.getElementById ('second');
if (t1.value != '') {
t2.setAttribute('disabled','disabled');
return true;
}
if (t2.value != '') {
t1.setAttribute('disabled','disabled');
return true;
}
}
</script>
</head>
<body>
...
<input type="text" id="first" onblur="verify()">
<input type="text" id="second" onblur="verify()">
...
</body>
You can't achieve this with plain HTML.
Following the guidelines of progressive enhancement, you should first implement a server side check in whatever form handler you are using to process the submitted data.
Then you can consider adding JavaScript for a client side check. Something along the lines of:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Disabling form controls</title>
</head>
<body>
<form id="myForm" action="http://example.com/">
<div>
<input name="t1">
<input name="t2">
</div>
</form>
<script type="text/javascript">
(function () {
var t1 = document.forms.myForm.elements.t1;
var t2 = document.forms.myForm.elements.t2;
var handler = function handler() {
t2.disabled = (t1.value !== "");
};
t1.onchange = handler;
}());
</script>
</body>
</html>
(Although I would use a library such as YUI or jQuery to add event handlers in a fashion that is better protected from overwriting in a crossbrowser compatible way).
You might want some tutorials on JavaScript and the DOM so that this makes sense.

Categories