javascript timed function - expected identifier - javascript

I am having a problem with a simple script that is supposed to update a page with some values(user input) that are turned from monthly to yearly (the numbers go into numeric fields created by confirmIT)
<script>
function update() {
for (var i = 0; i < 9; i++) {
var ans = parseInt(document.getElementById("bq10a_" + i).value, 10);
if (!isNaN(ans)) {
var new = ans * 12;
document.getElementById("bq10a_" + i + "calc").value = new;
}
}
}
return;
}
setInterval("update()", 1000);
</script>
this yields an Expected identifier error on line
var new = ans*12;
and i would appreciate any help on how to solve it

The word new is a reserved word in JavaScript and cannot be used as the name of a variable.
The error means that the parser expected an "identifier", which is to say that it expected to see a valid identifier.
Change the name of the variable and things should improve. In the code you've posted I think there's a { } nesting problem; there appears to be one too many before the return of the function.
edit — also as jbabey notes in a comment, your setInterval() call should be
setInterval(update, 1000);
It's not a good idea, generally, to pass strings to setInterval(), despite the advice of thousands of mouldy old instructional websites.

Word "new" -- is special in javascript language:
line is incorrect:
var new = ans*12;
try this:
var newvalue = ans*12;
More information on:
http://javascript.about.com/library/blreserved.htm
http://www.ecma-international.org/publications/standards/Ecma-262.htm

Related

How do I put together string variables in Javascript? It's just saying "Object Undefined"

I have tried for so long to get this code to work. I'm programming a little game when you need to be fast, so I made a stopwatch. But the stopwatch just doesn't want to work. Instead of the seconds the stopwatch is showing Object Undefined and I don't know why. This is the code i'm using:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
stopwatchFrame+=1;
stopwatchSeconds = floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = toString(stopwatchSeconds);
var = "Total time: " + stopwatchSecondsString + " seconds";
I'm using a simple website called Koda.nu, it's a Swedish website for young to learn programming in JS. Some functions is coming from their built in source. I'm new to programming so that's why.
You are missing a variable name where you have a value of "Total time: " + stopwatchSecondsString + " seconds"; It should be:
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
Also read what #Jaromanda X wrote in the comments section. It should be like this:
stopwatchSeconds = Math.floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
We don't have an access to your updatesPerSecond variable so that would throw an error as well. If declared, your code would work like this:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
var updatesPerSecond = 0;
stopwatchFrame += 1;
stopwatchSeconds = Math.floor(stopwatchFrame / updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
You dont have a variable name in the last line, and if this is all your code, then you dont initialize updatesPerSecond, meaning you dont have a line like
var updatesPerSecond = somenumberhere
If you name your last variable and initialize updatesPerSecond then you should be fine.
However I dont know anything about this website, but I quess it's old. Here is some advice.
You need to tell javascript, that floor is a function from Math so use Math.floor, maybe it works in this website like you did, but keep in mind that you should use it otherwise.
toString() doesnt work like that. Again I dont know if they are using some different methods, but normal js toString() works like number.toString() and u can pass the radix as a parameter, meaning the base of the number representation (2 for binary, 16 for hexadecimal etc.) but this is optional, default is 10 for decimal.
Dont use var as a declaration. Use let instead, if the variable will change, and use const if it wont. In your case you should use let everywhere.
Other thing is that you can use the ++ operator to increment a value by 1, so instead of stopwatchFrame+= 1 just use stopwatchFrame++
And last you shouldn't initialize your default string value as "Nothing", it should be "", an empty string or undefined or null.
I hope this helps, have a good day!

Running script function from editor doesn't work as expected

So, I never ever programmed JavaScript and never did anything with Google Script before either. I have a fairly good understanding of Visual Basic and macros in Excel and Word. Trying to make a fairly basic program: Plow through a list of variables in a spreadsheet, make a new sheet for each value, insert a formula in this new sheet, cell (1,1).
Debug accepts my program, no issues - however, nothing at all is happening when I run the program:
function kraft() {
var rightHere =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
var goshDarn = "";
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getTextStyle();
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed.isBold == false) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,500);
thisOne.deleteColumns(5, 23);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015,'Individuelle varer'!A16:A30015=" & Char(34) & vaerdi & Char(34) & ")))");
}
}
}
activeSheet could be called by name, so could activeSpreadsheet, I guess. But range A1:A131 has a ton of variables - some times there are empty lines and new headers (new headers are bold). But basically I want around 120 new sheets to appear in my spreadsheet, named like the lines here. But nothing happens. I tried to throw in a log thingy, but I cannot read those values anywhere.
I must be missing the most total basic thing of how to get script connected to a spreadsheet, I assume...
EDIT: I have tried to update code according to tips from here and other places, and it still does a wonderful nothing, but now looks like this:
function kraft() {
var rightHere = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
var goshDarn = "";
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getFontWeight();
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed.isBold == false) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,500);
thisOne.deleteColumns(5, 23);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015,'Individuelle varer'!A16:A30015=" + "\"" + vaerdi + "\"" + ")))");
}
}
}
EDIT2: Thanks to exactly the advice I needed, the problem is now solved, with this code:
function kraft() {
var rightHere = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getFontWeight()
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed != "bold") {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,499);
thisOne.deleteColumns(5, 20);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015;'Individuelle varer'!A16:A30015=" + "\"" + vaerdi + "\"" + "))");
}
}
}
There are multiple issues with your script, but the main one is that you never actually call the isBold() function in your 'if' statement.
if (value && format.isBold() == false) {
//do something
}
Because you omitted the parentheses in 'fed.isBold', the expression never evaluates to 'true'. 'isBold' (without the parentheses) is of type Object as it's a function.
There are other issues that prevent the script from running properly:
Not using the 'var' keyword to declare variables and polluting the global scope. As a result, all variables you declare within your 'for' loop are not private to your function. Instead, they are attached to the global object and are accessible outside the function. https://prntscr.com/kjd8s5
Not using the built-in debugger. Running the function is not debugging. You should set the breakpoints and click the debug button to execute your function step-by-step and examine all values as it's being executed.
Deleting the non-existent columns. When you create the new sheet, you call the deleteColums(). There are 26 columns in total. The 1st parameter is the starting column while the 2nd one specifies how many columns must be deleted. Starting from column 5 and telling the script to remove 23 columns will throw an exception. Always refer to the documentation to avoid such errors.
console.log doesn't exist within the context of the Script Editor. You are NOT executing the scripts inside your browser, so Browser object model is not available. Use Logger.log(). Again, this is detailed in the documentation.
Your formula is not formatted properly.
JS is a dynamically typed language that's not easy to get used to. If you don't do at least some research prior to writing code, you'll be in for a lot of pain.

Error: unexpected token ';' at the end of a javascript statement

Just a side note before you try to help: I am a complete newbie. Try to keep things simple ;)
I am trying to code a way to store var values between webpages in HTML. So far I have not been very successful. The problem I am having at the moment is the error 'unexpected token, ';'' (when I paste it into the console on 'Ctrl+Shft+J'
var cookieString = document.cookie;
var savedStats = 0;
var stats = 0;
var fsStat = 0;
var psStat = 0;
var testStat = 0;
function getStats() {
function splitCookieString() {
return savedStats = cookieString.split(',');
}
return stats = [savedstats[0], savedStats[savedstats.length - 1];
return fsStat += stats[0];
return psStat += stats[1];
return testStat = 'Hello World!';
}
}
and it points to the end of the line:
return stats = [savedstats[0], savedStats[savedstats.length -1];
Please help me! Also while I'm here, the Function 'getStats()' has a wierd thing going on where it makes me put two '}' to end it.
The code you posted shows some problems around the understanding of:
The return keyword (structured programming)
The assignment operator (=) (imperative programming)
I strongly recommend to develop some understanding of these concepts.

Javascript Simple If Else innerHTML == 'something' not working

I have a seemingly simple javascript function I am trying to create that checks the value of an elements innerHTML and spits out a value based on the answer, but for the life of me I can't get it to work and don't get any errors. This function is triggered by onclick events and doesn't need to have window.onload added. Any insight anyone could give me would be much appreciated! Here is my HTML
<div class="col-md-8 col-xs-9 product-info">
<p id="planTitle" class="bold m-b-2">20 DAY SUPPLY // 40 CAPSULES // FMF</p>
<p>Price: <span class="pull-right" id="plan-amount">$79</span></p>
<p>Tax: <span class="pull-right">Included</span></p>
<p id="shipping-line">Shipping: <span class="pull-right" id="cart-shipping-cost">$9.99</span></p>
<p class="hidden">Coupon: <span class="pull-right" id="coupon-code">firstmonthfree20day</span></p>
</div>
And my Javascript
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleesd = document.getElementById('planTitle').innerHTML;
console.log(planTitleesd);
if (planTitleesd == '10 Day Supply // 20 Capsules // FMF') {
kkdk = '5.99';
console.log(kkdk);
} else if (planTitleesd == '20 Day Supply // 40 Capsules // FMF') {
kkdk = '9.99';
console.log(kkdk);
} else if (planTitleesd == '30 Day Supply // 60 Capsules // FMF') {
kkdk = '14.99';
console.log(kkdk);
}
}
Oddly, console.log(planTitleesd) returns a value, such as
"20 DAY SUPPLY // 40 CAPSULES // FMF"
but all the other console.log(kkdk) do not. Thanks for your help!
I have updated the original question with the relevant HTML, sorry about that.
You are doing a case-sensitive comparison. You've indicated that the resultant value is all caps, while you're comparing it to Title Case. Consider doing a case-insensetive comparison by calling toLowerCase on both operands before comparison. Also, please actually post your markup. Troubleshooting code questions must contain an MCVE. – CollinD 9 mins ago
This was the simple answer to the simple question I was looking for - Thanks CollinD!
Almost for sure you have newline at the beginning/end of planTitleesd.
Try to replace console.log(planTitleesd); by console.log('>' + planTitleesd + '<'); to check that.
Here is an example:
https://jsfiddle.net/324aw9zz/1/
You should avoid any spaces/newline between the tag opener/closer and the text itself:
<th id=planTitle>lala</th>
instead of
<th id=planTitle>
lala
</th>
Why not do something more along the lines of:
Using .indexOf() to check for one (or multiple) Strings?
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleesd = document.getElementById('planTitle').innerHTML;
if ( planTitleesd.indexOf('10 Day') > -1 && planTitleesd.indexOf('20 Capsules') > -1 ) {
kkdk = '5.99';
} else if (planTitleesd.indexOf('20 Day')) {
kkdk = '9.99';
} else if (planTitleesd.indexOf('30 Day')) {
kkdk = '14.99';
}
}
I also agree that you should remove the case sensitive strings, as, (once again), typos and the like can occur.
Chances are there is just a typo in the value, or perhaps an empty return/newline you may be looking over.
Make sure all Carriage Returns and more are removed from the response. Seeing as, some items may actually add one that you do not notice. (Such as an openly tabbed div)
It sounds like this app is a store, something that could get pretty big. I would suggest is maybe an object that returns back the result you need.
The following a JSFiddle that I feel would simplify your process if you could create a proper JSON object.
https://jsfiddle.net/0sscf798/
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleArr = [];
var planTitleObj = {};
var planTitleesd = document.getElementById('planTitle').innerHTML;
// This would most likely be a JSON response of items from the page/category
planTitleObj = {
"10 Day Supply": {
"20 Capsules": {
"FMF": 1.23
}
},
"20 Day Supply": {
"20 Capsules": {
"FMF": 4.56
}
}
};
planTitleArr = planTitleesd.split(" // ");
var price = planTitleObj[planTitleArr[0]][planTitleArr[1]][planTitleArr[2]] || "There is a problem with the price."
alert("The Price is: " + price);
}
updateShippingCost('');

Regex not matching properly

Ive been working on this regex for days now and I cant get it figured out. It either passes everything I put in there or it kicks everything out and I cannot seem to make it function. Admittedly I am new to doing this complex of stuff with Javascript so It may be that you realy cant do this.
I want to check onkeypress what was entered into the input and then validate it to x, y, or z. Then from there send it on about its way to do other neat stuff.
So the question is what the heck am I not understanding about RegExp?
Here is a FIDDLE for it.
function val() {
var gradeIn = document.querySelectorAll("#letGrade input[type=text]");
var checkGrade = new RegExp(/[xyz]/gi);
for (var i = 0; i < gradeIn.length; i++) {
if (!checkGrade.test(gradeIn.value)) {
alert ("This must be X, Y, or Z");
return false;
} else {
return true;
}
}
};
EDIT/UPDATE:
I was trying to do this on keypress and validate each text input individualy however this was realy kinda squishy in the grand scheme of things and not working out exactly correct. I decided to validate all text inputs onsubmit and have everything go all at once. Updated code is below.
function calcGPA() {
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be A, B, C, D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
gVals.push(grades[i].value);
cVals.push(contacts[i].value);
}
//Other cool stuff happens here
};
Now to just finish the conversion piece for the letters to numbers and the math piece. Thank you for your help on this!
The problem's not only with your regular expression.
if (!checkGrade.test(gradeIn[i].value)) {
You weren't checking each grade. Now if you want it to only be those characters, you have to extend the regular expression a bit. Also, there's no point calling new RegExp if you're using native syntax.
var checkGrade = /^[xyz]+$/;
That means that you're OK with the fields being like "xxyyz" or "zzy". If it should just be one character, that'd be
var checkGrade = /^[xyz]$/;

Categories