Good day,
I'm coding a simple calculation price based on:
A single price
The frequency of that price (Weekly, daily, etc.).
I keep having the word "undefined" being printed out in the page. I've tried to redefine all the variable of that part. All variables are correctly defined. Do you guys see any error in my code below?
//parking cost
var parking_cost1 = 0;
var parkingCostUnity1 = 0;
var parkingCostFrequency1 = 0;
parking_cost1 = new Number(document.getElementById("parking_cost1").value);
parkingCostFrequency1 = document.getElementById("parking_cost1_frequence1").value;
if (parkingCostFrequency1 == "per_night") {
parkingCostUnity1 = result;
}
if (parkingCostFrequency1 == "per_week") {
parkingCostUnity1 = nrOfWeeks;
}
if (parkingCostFrequency1 == "per_month") {
parkingCostUnity1 = nrOfMonths;
}
var echoParkingCostFrequency1 = parkingCostFrequency1.replace("_", " ");
var totalParkingCost1 = 0;
totalParkingCost1 = parkingCostUnity1 * parking_cost1;
if (totalParkingCost1 > 0) {
var printOutTotalParkingCost1 = '<tr><td><b>Total parking cost</b></td><td>' + parking_cost1 + ' ' + currency + ' ' + echoParkingCostFrequency1 + '</td><td>' + totalParkingCost1 + ' ' + currency + '</td></tr>';
}
<i class="fas fa-parking"></i> <text class="form_basic_text" />Parking cost<br>
<input type="number" onChange="resume()" name="parking_cost1" id="parking_cost1" class="form_basic_field_bid" style="width:auto;" /><br/>
<center>
<select onChange="resume()" name="parking_cost1_frequence1" id="parking_cost1_frequence1" style="width:auto;height:25px;padding:0px;width:auto;">
<option value="per_night">Per night</option>
<option value="per_week">Per week</option>
<option value="per_month">Per month</option>
</select>
</center>
The following variables have already been defined in the document:
//var currency
var currency = document.getElementById("currency").value;
//This variable is always defined, as it's a dropdown.
//var result, nrOfWeeks and nrOfMonths are all under the same parameters
//check-in date
var checkInDate = new Date(document.getElementById("check_in_date").value);
var checkInDateResume = checkInDate.getDate() + '-' + (checkInDate.getMonth()+1) + '-' + checkInDate.getFullYear();
if(checkInDateResume=="NaN-NaN-NaN"){
checkInDateResume = "<text class='alert'>Not defined yet</text>";
result = 1;
nrOfWeeks = 1;
nrBiWeeks = 1;
nrOfMonths = 1;
}
var checkOutDate = new Date(document.getElementById("check_out_date").value);
var checkOutDateResume = checkOutDate.getDate() + '-' + (checkOutDate.getMonth()+1) + '-' + checkOutDate.getFullYear();
if(checkOutDateResume=="NaN-NaN-NaN"){
checkOutDateResume = "<text class='alert'>Not defined yet</text>";
result = 1;
nrOfWeeks = 1;
nrBiWeeks = 1;
nrOfMonths = 1;
}
//Since the nr of months, week and result (the number of nights) is the difference between the check-in and check-out date - Those aren't defined except as mentionned up here. We then define the rest of the vars
var difference = Math.abs(checkOutDate-checkInDate);
var result = difference/(1000*3600*24);
var nrOfMonths = Math.ceil(result/30.41);
var nrOfWeeks = Math.ceil(result/7);
Thank you!
Edit: It's my first time posting here. Thank you for your patience and your comments on how to make my question more understandable!
I did some extended research and discovered my mistake:
I forgot to add an else to the the last IF statement.
if(totalParkingCost1>0){
var printOutTotalParkingCost1 = 'XYZ';
}
The var printOutTotalParkingCost1 was used in any scenario. I added the following else
else{
var printOutTotalParkingCost1 = "";
}
Now, the variable printOutTotalParkingCost1 is defined whatever the scenario is. Thank you all for your kind help! Thanks to #ivar for his extensive explanations.
Related
First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME
I am fairly new to the Javascript language.
I am trying to make a clicker game (not so hard). The game is working but I am trying to make a save method for the game.
Instead of cookies I decided to have the game make its own code where the user can copy and paste it the next time they get on the game.
So the save method works but when I try to have the game load the code it doesn't quite do it right.
Instead of grabbing the values before the commas it grabs the letters of the word I use as a checker.
Is there a way I can fix this?
Here's my code:
var shovel = 0;
var miner = 0;
var loaders = 0;
var drill = 0;
var tnt = 0;
var minecart = 0;
var bulldozer = 0;
var trucks = 0;
var manager = 0;
var cost1 = 10;
var cost2 = 200;
var cost3 = 350;
var cost4 = 500;
var cost5 = 600;
var cost6 = 800;
var cost7 = 2500;
var cost8 = 6000;
var cost9 = 100000;
var cash = 0;
var cashRate = 1000;
//-- SAVE GAME --
function save() {
var save = "";
var data = cash + "," + cashRate + "," + shovel + "," + miner + "," + loaders + "," + drill + "," + tnt + "," + minecart + "," + bulldozer + "," + trucks + "," + manager + "," + cost1 + "," + cost2 + "," + cost3 + "," + cost4 + "," + cost5 + "," + cost6 + "," + cost7 + "," + cost8 + "," + cost9;
save += "CoalMinerGame=" + data;
var finalSave = encode(save);//Encoding/Decoding is done using the Base64 Code
prompt("Keep this somewhere you'll remember!", finalSave);
}
function load() {
var code = prompt("Paste the save code below!", "");
if (code != "") {
var load = decode(code);
if (load.includes("CoalMinerGame=")) {
load.split("CoalMinerGame=");
//load[0] = blank
cash = load[1];
cashRate = load[2];
shovel = load[3];
miner = load[4];
loaders = load[5];
drill = load[6];
tnt = load[7];
minecart = load[8];
bulldozer = load[9];
trucks = load[10];
manager = load[11];
cost1 = load[12];
cost2 = load[13];
cost3 = load[14];
cost4 = load[15];
cost5 = load[16];
cost6 = load[17];
cost7 = load[18];
cost8 = load[19];
cost9 = load[20];
updateWorkers();
alert("Save Successfully Loaded!");
} else {
alert("Not a valid save code!");
}
} else {
alert("You must enter a save code to get your game back!");
}
}
Save
Load
I see two mistakes :
The load.split() function does not modify load but returns an array instead, an array that you should store in another variable.
You should also split once again the resulting string on commas to separate your different values.
Hope it helps!
Oh man, this code is giving me a pain :).
What about use some native functions for whole objects so you dont have to manually serialize it and deserialize it?
This code
const myObject = {
some: 'fields',
even: {
nested: 'fields',
},
};
const stringified = JSON.stringify(myObject);
console.log(stringified);
const unstringified = JSON.parse(stringified);
console.log(unstringified);
Is having this output
{"some":"fields","even":{"nested":"fields"}}
{ some: 'fields', even: { nested: 'fields' } }
You can also use base64 steps to code and decode
The JSON.stringify take JS object and create pure string which contains JSON inside.
Then when you want to take JSON and create object from it, you can just JSON.Parse, which expects string.
I echo the sentiment to use JSON. My example below might require some refactoring in the game code but would be cleaner. To access the variable cash you would just use gameData.cash where you currently are using the cash var.
var gameData = {
cash: 0,
cashRate:0,
shovel:0,
miner:0,
loaders:0,
drill:0,
tnt:0,
minecart:0,
bulldozer:0,
trucks:0,
manager:0,
cost1:10,
cost2:200,
cost3:350,
cost4:500,
cost5:600,
cost6:800,
cost7:2500,
cost8:6000,
cost9:100000
}
function save(){
var dataToSave = CoalMinerGame: {
cash: cash,
cashRate:cashRate,
shovel:shovel,
miner:miner,
loaders:loaders,
drill:drill,
tnt:tnt,
minecart:minecart,
bulldozer:bulldozer,
trucks:trucks,
manager:manager,
cost1:cost1,
cost2:cost2,
cost3:cost3,
cost4:cost4,
cost5:cost5,
cost6:cost6,
cost7:cost7,
cost8:cost8,
cost9:cost9
}
var finalSave = JSON.Stringify(dataToSave)
finalSave = encode(finalSave)
prompt("Keep this somwhere you'll remember!", finalSave)
}
function load(){
var code = prompt("Paste the save code below!", "")
var load = decode(code)
if (code != ""){
gameData = load;
updateWorkers();
alert("Save Successfully loaded!")
} else {
alert("You must enter a save code to get your game back!")
}
}
I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;
I'm receiving NotANumber for my total from movieTotal, as well as im not getting the correct value of adding pricePerTicket + pricePerDinner. Can someone help me figure out what im doing wrong?
<script type="text/javascript">
<!--
var ticket, earlyBirdTicket, WeekDinner, weekendDinner, numberOfTickets, TotalDue;
var numberOfTickets, pricePerTicket, pricePerDinner, costOfDandT, totalAmountOwed;
var totalDandT, yes, week, movieTotal;
var ticket = 5;
var nightTicket = 10;
var weekDinner = 8;
var weekendDinner = 12;
var yes = ticket;
var week = weekDinner;
var movieTotal = totalDandT * numberOfTickets;
totalDandT = pricePerDinner + pricePerTicket;
numberOfTickets = prompt ("How many tickets?");
pricePerTicket = prompt ("Is this earlybird? yes/no ");
pricePerDinner = prompt ("weekend or weekday? week/weekend ");
pricePerTicket = parseInt(pricePerTicket);
pricePerDinner = parseInt(pricePerDinner);
movieTotal = parseInt (movieTotal);
if (pricePerTicket = yes)
{
pricePerTicket = ticket;
}
else
{
pricePerTicket = nightTicket;
}
if (pricePerDinner = week)
{
pricePerDinner = weekDinner;
}
else
{
pricePerDinner = weekendDinner;
}
document.write ("<br>Number of tickets sold : " + numberOfTickets);
document.write ("<br>Cost per ticket tonight : $" + pricePerTicket);
document.write ("<br>Cost per dinner tonight : $" + pricePerDinner);
document.write ("<br>Cost of dinner and ticket : $" + pricePerTicket + pricePerDinner);
document.write ("<br> Your total today is $" + movieTotal);
// -->
</script>
You have not initialized the variables. You should do it before using them.
Uninitialized variables are equals to undefined so yes.undefined plus undefined is not a number.
I'm having a problem with an undefined variable error. This is my code:
window.sys.Bash = {};
window.sys.Bash.version = "";
window.sys.Bash.version.major = 0;
window.sys.Bash.version.minor = 1;
window.sys.Bash.version.build = 1;
window.sys.Bash.version.release = "beta";
window.sys.Bash.printing = false;
window.sys.Bash.queue = Array();
window.sys.Bash.span = bash;
window.sys.Bash.span.input = input;
window.sys.Bash.version = ""
+ window.sys.Bash.version.major + "."
+ window.sys.Bash.version.minor + "."
+ Array(2-window.sys.Bash.version.build.toString().length+1).join('0')
+ window.sys.Bash.version.build + "-"
+ window.sys.Bash.version.release + " "
+ "(x86_64-" + window.sys.platform + ")";
delete bash; delete input;
My Web console says, that window.sys.Bash.version.build is undefined on this line:
+ Array(2-window.sys.Bash.version.build.toString().length+1).join('0')
I copied the code from here, so I don't know much about it, but it should work, huh?
You defined version as primitive, rather than object. Try this:
window.sys.Bash.version = {};
window.sys.Bash.version.major = 0;
window.sys.Bash.version.minor = 1;
window.sys.Bash.version.build = 1;
Adding properties to primitive is not an error, but the properties will be added to a temporary object that is then lost. Basically, this happened:
window.sys.Bash.version = "";
new String(window.sys.Bash.version).major = 0;
new String(window.sys.Bash.version).minor = 1;
new String(window.sys.Bash.version).build = 1;
This is described here:
Let O be ToObject(base).
Which is effectively the same as Object(str), which is effectively the same as new String(str)