JavaScript else if not working - javascript

I have a simple screen with 2 text boxes, one to enter Methane data, One ot enter Hydrogen Data, I have written a little JS to divide one by the other. As below.
<script type="application/javascript">
function RRC()
{
var Methane = document.getElementById('MethaneVPM').value;
var Hydrogen = document.getElementById('HydrogenVPM').value;
var RRC1 = Methane / Hydrogen;
var RRR1 = parseFloat(RRC1).toFixed(1);
if (!isNaN(RRR1))
{
document.getElementById('RogerRatio').value = RRR1;
}
}
</script>
This works with an on focus, If I put 62 in Methane and 52 in Hydrogen I get 1.2, which is correct.
However when I add some else if statements to it, it fails.
I've been looking at this for days now, I know I am missing something I just can't work out what.
So below just stops responding.
<script type="application/javascript">
function RRC()
{
var Methane = document.getElementById('MethaneVPM').value;
var Hydrogen = document.getElementById('HydrogenVPM').value;
var RRC1 = Methane / Hydrogen;
var RRR1 = parseFloat(RRC1).toFixed(1);
var RRC1R = 0;
if(RRR1 < 0.1){RRC1R = 5;}
else if(RRR1 >= 0.1 && < 0.9){RRC1R = 0;}
else if(RRR1 >= 1 && < 2.9){RRC1R = 1;}
else if(RRR1 >= 3){RRC1R = 2;}
else {RRC1R = 'Boo';}
if (!isNaN(RRC1R))
{
document.getElementById('RogerRatio').value = RRC1R;
}
}
</script>
Any pointers at this stage would be a huge help.
Thanks in advance

You're missing a value in your if statements:
else if(RRR1 >= 0.1 && < 0.9)
should be
else if(RRR1 >= 0.1 && RRR1 < 0.9)
the same goes for all conditions
see the working code here

You are missing RRR1 in your conditions. I would also suggest to change condition as follows:
<script type="application/javascript">
function RRC()
{
var Methane = document.getElementById('MethaneVPM').value;
var Hydrogen = document.getElementById('HydrogenVPM').value;
var RRC1 = Methane / Hydrogen;
var RRR1 = parseFloat(RRC1).toFixed(1);
var RRC1R = 0;
if(RRR1 < 0.1){RRC1R = 5;}
else if(RRR1 >= 0.1 && RRR1 < 1){RRC1R = 0;}
else if(RRR1 >= 1 && RRR1 < 3){RRC1R = 1;}
else if(RRR1 >= 3){RRC1R = 2;}
else {RRC1R = 'Boo';}
if (!isNaN(RRC1R))
{
document.getElementById('RogerRatio').value = RRC1R;
}
}
</script>

Related

How to fix 'ReferenceError: hello is not defined' when it is

I'm trying to code a game and I want to make it so that when you click a button, it increases the number. My game is like a mining game and you click to get ores and at the top right is a box which tells you what you are mining and you can see what you are mining, except when I click the mine button, it comes with the error which says ReferenceError: hello is not defined. The function hello is the function which gives you the ores.
I have tried fixing up some other functions which give you helpers in exchange for help but it didn't change anything, also I checked on stack overflow, but there wasn't anything that could help me. (Keep in mind I am 10 years old)
HTML:
<div class="mwrapper">
<button id="minebutton" onclick="hello()">Mine!</button>
</div>
JavaScript:
//defining the vars.
var stonei = 0;
var deepness = 0;
var stone = 0;
var silveri = 0;
var silver = 0;
var goldi = 0;
var gold = 0;
var platinumi = 0;
var platinum = 0;
var diamondi = 0;
var diamond = 0;
var alexandritei = 0;
var alexandrite = 0;
var amethysti = 0;
var amethyst = 0;
var unobtaniumi = 0;
var unobtanium = 0;
var emeraldi = 0;
var emerald = 0;
var tubi = 0;
var tub = 0;
var blockN;
var block = 0;
var money = 0;
var stoneSold = 0;
var silverSold = 0;
var goldSold = 0;
var clickers = 0;
var moneyEver = 0;
var BpS = 0;
//defining element to shorten code later
var blockEl = document.getElementById("block");
var btxtEL = document.getElementById("btxt");
var moneyEl = document.getElementById("money");
//changing what the 'Block you are mining' says
var findBlock = function(b) {
if (b === 0) {
blockEl.style.backgroundColor = "grey";
btxt.innerHTML = "Stone";
blockN = "stone";
}
else if (b === 1) {
blockEl.style.backgroundColor = "silver";
btxt.innerHTML = "Silver";
blockN = "silver";
}
else if (b === 2) {
blockEl.style.backgroundColor = "gold";
btxt.innerHTML = "Gold";
blockN = "gold";
}
else if (b === 3) {
blockEl.style.backgroundColor = "rgb(90, 89, 89)";
btxt.innerHTML = "Platinum"
blockN = "platinum";
}
else if (b === 4) {
blockEl.style.backgroundColor = "rgb(185, 242, 255)";
btxt.innerHTML = "Diamond"
blockN = "diamond";
}
else if (b <= 10) {
btxt.innerHTML = "Not coded yet";
}
//hehe
else {
btxt.innerHTML = "WHAAAA?????????";
}
}
//adds materials to the left sidebar
var createBlock = function(b) {
if (b === 0) {
stonei += 1;
stone += 1;
document.getElementById("stonei").innerHTML = stonei;
document.getElementById("stone").innerHTML = stone;
}
else if (b === 1) {
silveri += 1;
silver += 1;
document.getElementById("silveri").innerHTML = silveri;
document.getElementById("silver").innerHTML = silver;
}
else if (b === 2) {
goldi += 1;
gold += 1;
document.getElementById("goldi").innerHTML = goldi;
document.getElementById("gold").innerHTML = gold;
}
else if (b === 3) {
platinumi += 1;
platinum += 1;
document.getElementById("platinumi").innerHTML = platinumi;
document.getElementById("platinum").innerHTML = platinum;
}
else if (b === 4) {
diamondi += 1;
diamond += 1;
document.getElementById("diamondi").innerHTML = diamondi;
document.getElementById("diamond").innerHTML = diamond;
}
//not coded rest
}
//From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//for finding the block when you mine
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//when you click the mine button it does this
var hello = function() {
if (deepness === stone + silver + gold + platinum + diamond && stone >= stonei && silver >= silveri && gold >= goldi && platinum >= platinumi && diamond >= diamondi && stoneSold == stone - stonei && moneyEver == money + clickers &&typeof hsjsahjkd === 'undefined' || hsjsahjkd === null) {
if (deepness <= 50) {
block = 0;
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 50, deepness < 150) {
block = getRandomInt(0, 2);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 150, deepness < 250) {
block = getRandomInt(0, 3);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 250, deepness < 350) {
block = getRandomInt(0, 4);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 350) {
block = getRandomInt(0, 5);
findBlock(block);
deepness += 1;
createBlock(block)
}
}
else {
btxt.innerHTML = "Cheater.";
stonei = 0;
deepness = 0;
stone = 0;
silveri = 0;
silver = 0;
goldi = 0;
gold = 0;
platinumi = 0;
platinum = 0;
diamondi = 0;
diamond = 0;
alexandritei = 0;
alexandrite = 0;
amethysti = 0;
amethyst = 0;
unobtaniumi = 0;
unobtanium = 0;
emeraldi = 0;
emerald = 0;
tubi = 0;
tub = 0;
stoneSold = 0;
silverSold = 0;
goldSold = 0;
clickers = 0;
moneyEver = 0;
BpS = 0;
console.log("You cheated. The game restarted.")
if (typeof hsjsahjkd == 'undefined') {
var hsjsahjkd = 1;
}
else {
hsjsahjkd += 1;
}
document.getElementById("cheat").innerHTML = hsjsahjkd;
}
}
Sorry, but the functions needed are quite long. If you want to see the whole code, go to megagames.me/games/mining.html
I expected the out put of hello() to increment some of the ores, but it gave ReferenceError: hello is not defined.
Make sure your JavaScript is linked in the head tag or above the button. Otherwise you'll be calling a function that doesn't exist yet. An easy way to remember is to think of it as a book, you read from top to bottom the same way JavaScript executes top to bottom.
Also, try using Let and Const instead of Var and try using Switch Cases instead of if else all over. :-)

Why my JS path-finder algorythm isn't work when I change the matrix

I've to make a code that run a matrix to find the sorthest path to '9' (only walking above the ones, and avoiding the zeros)
In the example below The result correct (5 steps), but if I change the matrix elements positions, the result came wrong..
What can I do? I appreciate any help.
var matrix =
[[1,1,1,1],
[0,1,1,0],
[0,1,0,1],
[0,1,9,1],
[1,1,1,1]]
function runMatrix(matrix){
newPos = 0;
var resultr;
var resultc;
for( var i = 0, lenR = matrix.length; i < lenR; i++ ) {
for(var j = 0, lenC = matrix[i].length; j < lenC; j++){
if( matrix[i][j] == 9 ) {
resultr = i;
resultc = j;
break;
}
}
}
for( var i = 0; i < resultr; i++ ) {
var k = 0;
if(matrix[i+1][k] == 1){
if(matrix[i+1][k+1] == 9 || matrix[i+1][k-1] == 9){
newPos = newPos + 2;
}else{
newPos = newPos + 1;
}
}else{
for(k = 1; k < resultc; i++){
if(matrix[i][k] == 1 || matrix[i][k] == 9){
newPos = newPos + 1
if(matrix[i+1][k] == 1){
if(matrix[i+1][k+1] == 9 || matrix[i+1][k-1] == 9){
newPos = newPos + 2;
}else{
newPos = newPos + 1;
}
i++;
break;
}
}
}
}
}
console.log("Steps: "+newPos)
}
runMatrix(matrix)
update
this matrix doens't work, for example:
[[1,1,1,1],
[0,0,0,1],
[0,0,0,1],
[0,0,9,1],
[0,0,0,0]]
It returns 4

missing ; before statement error on google Script

I try my first steps in google script and I try to calculate the percentile of a given range of numbers in a row. I always got a
Missing ; before statement. (line 107, file "Sitan_Code") error
I don't see the point, why I get this.
could anybody help?
Thanks in advance
function percentile() {
var tenPercent = 10 / 100; //simsSheet.getRange("I5").getValue() / 100;
var twentyfivePercent = 25 / 100; //simsSheet.getRange("I6").getValue() / 100;
var fiftyPercent = 50 / 100; //simsSheet.getRange("I7").getValue() / 100;
var seventyfivePercent = 75 / 100; //simsSheet.getRange("I8").getValue()/ 100;
var neintyPercent = 90 / 100; // simsSheet("I9").getValue() / 100;
var values = simsSheet.getRange("A1:NTP1").getValues().sort();
var percentage = [tenPercent, twentyfivePercent, fiftyPercent, seventyfivePercent, neintyPercent];
for (i = 0; i < percentage.length; i++) {
var index = values.length * percentage[i];
if ((index % 2) === 0) {
var average = (index[i] + index[i + 1]) / 2;
if (percentage[i] == percentage[tenPercent]) {
var ten = simsSheet.getRange("K5") set.Value(average);
} else if (percentage[i] == percentage[twentyfivePercent]) {
var twentyfive = simsSheet.getRange("K6").setValue(average);
} else if (percentage[i] == percentage[fiftyPercent]) {
var fivty = simsSheet.getRange("K7").setValue(average);
} else if (percentage[i] == percentage[seventyfivePercent]) {
var seventyfive = simsSheet.getRange("K8").setValue(average);
} else if (percentage[i] == percentage[neintyPercent] {
var neinty = simsSheet.getRange("K9").setValue(average);
else {
inx = Math.round(index);
}
Your code seems to be missing a few braces and periods that causes the compilation to fail, refer to the version below:
function percentile() {
var tenPercent = 10 / 100; //simsSheet.getRange("I5").getValue() / 100;
var twentyfivePercent = 25 / 100; //simsSheet.getRange("I6").getValue() / 100;
var fiftyPercent = 50 / 100; //simsSheet.getRange("I7").getValue() / 100;
var seventyfivePercent = 75 / 100; //simsSheet.getRange("I8").getValue()/ 100;
var neintyPercent = 90 / 100; // simsSheet("I9").getValue() / 100;
var values = simsSheet.getRange("A1:NTP1").getValues().sort();
var percentage = [tenPercent, twentyfivePercent, fiftyPercent, seventyfivePercent, neintyPercent];
for (i = 0; i < percentage.length; i++) {
var index = values.length * percentage[i];
if ((index % 2) === 0) {
var average = (index[i] + index[i + 1]) / 2;
if (percentage[i] == percentage[tenPercent]) {
var ten = simsSheet.getRange("K5").setValue(average);
} else if (percentage[i] == percentage[twentyfivePercent]) {
var twentyfive = simsSheet.getRange("K6").setValue(average);
} else if (percentage[i] == percentage[fiftyPercent]) {
var fivty = simsSheet.getRange("K7").setValue(average);
} else if (percentage[i] == percentage[seventyfivePercent]) {
var seventyfive = simsSheet.getRange("K8").setValue(average);
} else if (percentage[i] == percentage[neintyPercent]) {
var neinty = simsSheet.getRange("K9").setValue(average);
} else {
inx = Math.round(index);
}
}
}
}

Javascript formatting of 10 or 11 digit phone numbers and recognizing a 1800 phone number

I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>

Javascript - Repeated if-statements don't work

My code works (doesn't fail), but it doesn't do the right thing.
I call the "generate" function every time i want to generate a new "chunk", passing a new number into the function each time its called. It generates the chunk fine, but it doesn't generate what I want it to generate.
I want it to generate either a space, a jump, a slide, or a gap, if the previous generation was a space. But if the previous generation wasn't a space, generate a space.
It doesn't do that. It sometimes generates 2 gaps, 2 jumps, or 2 slides after each other and i have no idea why... ???
Here is my code:
var ptg = 'space'; // what was previously generated to top
var wtgt; // what is currently being generated to top
var chunktogenerateto = 0;
function generate(a){
chunktogenerateto = a;
var rand1 = Math.floor(Math.random()*100) + 1;
if(ptg == 'space' && rand1 <= 25){
wtgt = 'space';
}
else if(ptg == 'space' && rand1 <= 50 && rand1 > 25){
wtgt = 'jump';
}
else if(ptg == 'space' && rand1 <= 75 && rand1 > 50){
wtgt = 'slide';
}
else if(ptg == 'space' && rand1 > 75){
wtgt = 'gap';
}
else{
wtgt = 'space';
}
ptg = wtgt;
topGen(wtgt);
}
function topGen(g){
document.getElementById('t' + chunktogenerateto).setAttribute('src','images/terrain/t' + g + '.png');
}
I hope it's not a typo... HELP!
Where the calls to "generate" are coming from:
var chunkpos = new Array();
chunkpos[0] = -100;
chunkpos[1] = 0;
chunkpos[2] = 100;
chunkpos[3] = 200;
chunkpos[4] = 300;
chunkpos[5] = 400;
chunkpos[6] = 500;
chunkpos[7] = 600;
chunkpos[8] = 700;
chunkpos[9] = 800;
chunkpos[10] = 900;
chunkpos[11] = 1000;
var temppos = new Array();
var time1;
var millis1;
var time2;
var millis2;
var millis3;
var firstreset = true;
var pos;
var poschange;
function moveLevel(){
if(firstreset == true){
resetTime();
}
var time2 = new Date();
var millis2 = time2.getTime();
var millis3 = millis2 - millis1;
poschange = Math.floor(millis3 / 5);
for(i = 0; i < chunkpos.length; i++){
temppos[i] = chunkpos[i] - poschange;
if(temppos[i] <= -150){
generate(i);
temppos[i] += 1200;
}
pos = temppos[i];
document.getElementById('chunk' + i).setAttribute('style','left: ' + pos + 'px;');
}
}
function resetTime(){
time1 = new Date();
millis1 = time1.getTime();
if(firstreset != true){
for(i = 0; i < chunkpos.length; i++){
chunkpos[i] = temppos[i];
}
}
firstreset = false;
setTimeout('resetTime()',1000);
}
Where the calls to "moveLevel" are coming from:
window.onload = function(){
if(test = 'runnable')
{
gameLoop();
}
else
{
document.getElementById('gm').innerHTML = (gm + 'Failed to run game.');
}
}
function gameLoop(){
if(currentscreen == 'playing'){
moveLevel();
}
setTimeout('gameLoop()',0);
}
Here is a download link to a zip file containing all of the code:
ParkourFreak.zip
The code i'm having trouble with is under scripts/generation.js.
The main game page (where the generation is visible is index.html.
Rather than each if statement starting with "if(ptg == 'space' ... etc" - do this first in one simple "if not space return space".
After that you can start on your random - that should work for you.
Roughly a quarter of the time you previously had a space, it will create another, because of this code:
if(ptg == 'space' && rand1 <= 25){
wtgt = 'space';
}
Note that it's creating a space when a space was previously created.
Side note:
There's no need for the && rand1 > 25 on this line:
else if(ptg == 'space' && rand1 <= 50 && rand1 > 25){
Since you previously had if(ptg == 'space' && rand1 <= 25){, it's impossible as of that line for rand1 to be <= 25 when ptg == 'space'.
(And similarly the && rand2 > 50 on the following condition.)
Are you sure you're incrementing chunktogenerateto?
It appears to stay at 0 with the current code, is that in a segment you haven't shown?
Edit: oh, it's the argument of the function. Try logging that variable, maybe that's the problem?
// elsewhere
var wtgts = ['space','jump','slide','gap'];
// in the function
if(ptg !== 'space') {
wtgt = 'space';
} else {
var randidx = Math.floor(Math.random()*4);
wtgt = wtgts[randidx];
}
Or even in the function:
var newidx = (ptg == 'space') ? Math.floor(Math.random()*4) : 0;
wtgt = wtgts[newidx];
The weights were equal, so just pick a random index from 0 to 3 and use that to pick an action from an array.
Separate the logic for ptg being space so that you only test for it once
Consider denoting the actions as numbers instead of strings, as the assignment, comparison etc will be faster and more robust.
I thought the problem lied with the generation, when in fact all I had to do to solve it was to change this:
if(temppos[i] <= -100){
generate(i);
temppos[i] += 1200;
}
to this:
if(temppos[i] <= -100){
generate(i);
chunkpos[i] += 1200;
temppos[i] += 1200;
}

Categories