An error in my while loop that does not always show - javascript

I am trying to make a random map generator.
The map is 24x24.
The error does not always show. When it does show it is in the "Do/While" loop at the end of the function.
Specifically in the "while" line.
function randKeyRoomsLoc(tempMap, dir, locked, room, displayRooms, before){
var location = [];//creates array to store rooms location
if (dir == "n" || dir == "w") {//if directions is NORTH or west
if (before) {
before = false;//if before is true turn to false
}else {
before = true;// if before is false turn to true
}
}
if (dir == "w" || dir == "e") {// if directions is W or E
var lockedRoom = locked[1];
}else {
var lockedRoom = locked[0];
}
for (var i = 0; i < room.length; i++) {//loops thru the rooms
if (before) {//are the rooms being place before locked?
var tempX = lockedRoom + 2;//limist the 2 spaces from the LR
x = Math.floor(Math.random()*(22 - tempX+1)+tempX);//limits the spawn
y = Math.floor((Math.random() * 24));
}else {//are the rooms being place after locked?
var tempX = lockedRoom - 2;//limist the 2 spaces from the LR
x = Math.floor(Math.random()*(tempX - 0 + 1) + 0);//limits
y = Math.floor((Math.random() * 24));
}
if (dir == "w" || dir == "e") {//needs to exchange X & Y if W or E
var tempX = y;
var tempY = x;
y = tempY;
x = tempX
}
if (tempMap[x][y] == "#") {//checks to see the room is empty
tempMap[x][y] = jQuery.extend(true, {}, room[i]);
displayMap[x][y] = displayRooms[i];
}else {//if its not empty
if(dir == "w" || dir == "e"){// IF W OR E--------------------
do {//excecute this once
if (x < 21) {//if Y is less than the end
x++;// we move Y one to the right
if (y < lockedRoom) {//if X is less than the X of locked room
y++;//moves X up
}else {//if X is = or more than the X of lock
y--;//moves it down
}
}else {//if Y is close to the end
x--;//we move it back 5 places
if (y < lockedRoom) {//if X is less than the X of locked room
y++;//moves X up
}else {//if X is = or more than the X of lock
y--;//moves it down
}
}
} while (tempMap[x][y] != "#");//check if room is empty,not loops
tempMap[x][y] = jQuery.extend(true, {}, room[i]);
displayMap[x][y] = displayRooms[i];
}else {// IF S OR N---------------------------------------
do {//excecute this once
if (y < 21) {//if Y is less than the end
y++;// we move Y one to the right
if (x < lockedRoom) {//if X is less than the X of locked room
x--;//moves X up
}else {//if X is = or more than the X of lock
x++;//moves it down
}
}else {//if Y is close to the end
y--;//we move it back 5 places
if (x < lockedRoom) {//if X is less than the X of locked room
x--;//moves X up
}else {//if X is = or more than the X of lock
x++;//moves it down
}
}
} while (tempMap[x][y] != "#");//check if room is empty,not loops
tempMap[x][y] = jQuery.extend(true, {}, room[i]);
displayMap[x][y] = displayRooms[i];
}
}
location.push([x,y]);//saves the location of the room
}
return location;//returns the locations of all the rooms
}

Related

Travel around the city in 10 steps

We travel around the city in 4 cardinal directions and can only take 10 steps and must return to the place where we started. My program breaks on tests (didn't come to the place where I started from). Where is the mistake? I know that it can be solved easier, but I would like to know what my mistake is
function isValidWalk(walk) {
let x = 0, y = 0;
let result = 0;
if(walk.length !== 10) {
return false;
}
for (let i = 0; i < 10; i++) {
if(walk[i] === 'n') {
x += 1;
}
else if(walk[i] === 's') {
x += -1
}
else if(walk[i] === 'w') {
y += -1;
}
else if(walk[i] === 'e') {
y += 1;
}
}
result = x + y;
if(result === 0) {
return true;
}
return false;
}
You need ot check x and y directly. Their values should be zero, because you can not go north and west to get a neutral position.
if (x === 0 && y === 0) return true;
return false;
For example look to this walk
NWSSEN
There you have a balanced north and south, as well west and east.

My code gets into an infinite loop when setting up in p5

I am having real trouble finding where my loop is. I run the code and it hangs. I am trying to make a circuits game where there are circuits for the user to connect. But I am getting stuck at square one even setting up the map to make sure it is solvable. There is an infinite loop but I can't find it I looked and looked... here is the code.`
//maxLength of circut board is the board
let theHighestMaxLength = 10;
let board;
let gridX = 10;
let gridY = 10;
let perX = 10;
let perY = 10;
//s is here so we don't have to pass it everywhere the square we are looking at in functions
let s=null;
//length and usedsquares and begin are here to be used across functions
let length=0;
let usedSquares=0;
let begin=null;
class Asquare {
constructor(x, y) {
this.x = x;
this.y = y;
this.isCircut = false;
this.isWire = false;
this.OtherCircut = null;
this.Left = null;
this.Right = null;
this.Top = null;
this.Bottom = null;
this.otherCircut = null;
this.isBlank = false;
}
drawSelf() {
if (this.isCircut) {
rectMode(CENTER)
var xx = max(this.otherCircut.x, this.x);
var yy = max(this.otherCircut.y, this.y);
fill(color(xx * 25, yy * 25, 0));
square((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
else if (this.isWire) {
fill(color(this.otherCircut.x * 20, this.otherCircut.y * 20, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
else if (this.isBlank) {
fill(color(0, 204, 0))
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
}
}
function handleWireMove(){
s.isWire = true;
//remember the starting circut
s.otherCircut = begin;
informAll(s);
//the length is used
length++;
}
function informAll() {
//tell all the other squares of s
if (s.x - 1 >= 0) {
board[s.x - 1][s.y].Right = s;
}
if (s.x + 1 < gridX) {
board[s.x + 1][s.y].Left = s;
}
if (s.y - 1 >= 0) {
board[s.x][s.y - 1].Bottom = s;
}
if (s.y + 1 < gridY) {
board[s.x][s.y + 1].Top = s;
}
//the used squares is now higher
usedSquares++;
}
function setup() {
createCanvas(gridX * perX, gridY * perY);
noLoop();
//fill the board with squares
board = new Array(gridX).fill(0).map(() => new Array(gridY).fill(0));
for (var x = 0; x < gridX; x++) {
for (var y = 0; y < gridY; y++) {
board[x][y] = new Asquare(x, y);
}
}
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if(s.isBlank||s.isCircut||s.isWire){continue;}
//begin at this square
begin = s;
//if there is some way to go
if (s.Left == null || s.Right == null || s.Top == null || s.Bottom == null) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength))
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null ? 1 : 0;
numOption = s.Right == null ? numOption + 1 : numOption;
numOption = s.Top == null ? numOption + 1 : numOption;
numOption = s.Bottom == null ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
length=9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove()
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
}
}
else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
}
function drawAll() {
board.forEach(a => a.forEach(b => b.drawSelf()));
}
function draw() {
background(gridX * perX);
drawAll();
}
The problem is in the setup function but I can't find it. Please help
The problem is that you compute the number of available numOption only based on whether the randomly selected grid square has unconnected slots (Left, Top, Right, or Bottom) without considering whether the value of s.x and s.y make it possible to select one of those directions). As a result your inner loop repeats infinitely because it never calls handleWireMove() and thus never increases length.
The code below is modified with some extra logging and it becomes obvious where the infinite loop is (it eventually prints 'we failed to make a choice. that is not good' forever):
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
console.log(usedSquares);
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if (s.isBlank || s.isCircut || s.isWire) {
continue;
}
//begin at this square
begin = s;
//if there is some way to go
if (
s.Left == null ||
s.Right == null ||
s.Top == null ||
s.Bottom == null
) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength));
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
console.log('beggining inner loop');
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null ? 1 : 0;
numOption = s.Right == null ? numOption + 1 : numOption;
numOption = s.Top == null ? numOption + 1 : numOption;
numOption = s.Bottom == null ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
console.log('no options, abort');
length = 9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove();
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
console.log('we failed to make a choice. that is not good');
}
console.log('exited inner loop');
} else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
Here is a working version that correctly checks not only if there is an opening to the Left/Top/Right/Bottom, but also if that direction is possible (not off the edge of the grid):
//maxLength of circut board is the board
let theHighestMaxLength = 10;
let board;
let gridX = 10;
let gridY = 10;
let perX = 10;
let perY = 10;
//s is here so we don't have to pass it everywhere the square we are looking at in functions
let s = null;
//length and usedsquares and begin are here to be used across functions
let length = 0;
let usedSquares = 0;
let begin = null;
class Asquare {
constructor(x, y) {
this.x = x;
this.y = y;
this.isCircut = false;
this.isWire = false;
this.OtherCircut = null;
this.Left = null;
this.Right = null;
this.Top = null;
this.Bottom = null;
this.otherCircut = null;
this.isBlank = false;
}
drawSelf() {
if (this.isCircut) {
rectMode(CENTER);
var xx = max(this.otherCircut.x, this.x);
var yy = max(this.otherCircut.y, this.y);
fill(color(xx * 25, yy * 25, 0));
square((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
} else if (this.isWire) {
fill(color(this.otherCircut.x * 20, this.otherCircut.y * 20, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
} else if (this.isBlank) {
fill(color(0, 204, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
}
}
function handleWireMove() {
s.isWire = true;
//remember the starting circut
s.otherCircut = begin;
informAll(s);
//the length is used
length++;
}
function informAll() {
//tell all the other squares of s
if (s.x - 1 >= 0) {
board[s.x - 1][s.y].Right = s;
}
if (s.x + 1 < gridX) {
board[s.x + 1][s.y].Left = s;
}
if (s.y - 1 >= 0) {
board[s.x][s.y - 1].Bottom = s;
}
if (s.y + 1 < gridY) {
board[s.x][s.y + 1].Top = s;
}
//the used squares is now higher
usedSquares++;
}
function setup() {
createCanvas(gridX * perX, gridY * perY);
noLoop();
//fill the board with squares
board = new Array(gridX).fill(0).map(() => new Array(gridY).fill(0));
for (var x = 0; x < gridX; x++) {
for (var y = 0; y < gridY; y++) {
board[x][y] = new Asquare(x, y);
}
}
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
console.log(usedSquares);
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if (s.isBlank || s.isCircut || s.isWire) {
continue;
}
//begin at this square
begin = s;
//if there is some way to go
if (
s.Left == null ||
s.Right == null ||
s.Top == null ||
s.Bottom == null
) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength));
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
console.log('beggining inner loop');
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null && s.x - 1 >= 0 ? 1 : 0;
numOption = s.Right == null && s.x + 1 < gridX ? numOption + 1 : numOption;
numOption = s.Top == null && s.y - 1 >= 0 ? numOption + 1 : numOption;
numOption = s.Bottom == null && s.y + 1 < gridY ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
console.log('no options, abort');
length = 9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null && s.x - 1 >= 0) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove();
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null && s.x + 1 < gridX) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null && s.y - 1 >= 0) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null && s.y + 1 < gridY) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
console.log('we failed to make a choice. that is not good');
}
console.log('exited inner loop');
} else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
}
function drawAll() {
board.forEach((a) => a.forEach((b) => b.drawSelf()));
}
function draw() {
background(gridX * perX);
drawAll();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
One closing though: this bug is a symptom of this code being horribly complicated and violating fundamental principles of good design such as not having shared global state that is updated as a side effect of function calls.

Make the code in a 'do - while' run once - Node.js

(Ik Its a stupid question) with the "do - while" the code runs multiple times at the same time (i putted a console.log('while') at the beginning, so it print 'while' when the code is executed) but I want to run it one time at a time. Here's an example:
Code:
let x = 100
let y = 100
do {
console.log('while')
/*
here there's a piece of code that let the user choose what want he to do
*/
let random = Math.floor(//random number between 1 and 2)
if (random == 1) {
y = y - 50
} else {
x = x - 50
} while (y >= 0 && x >= 0 )
Obviously the console prints 'while' until the process ends.
I tried to use for (let i; i < 100; i++) and in the for i putted a if ( y <= 0 && x <= 0) but I can't start-over the loop (I dont know how to use continue).
The main problem with your code is the brackets - your formatting is incorrect:
let x = 100
let y = 100
do {
//...
if (random == 1) {
y = y - 50
} else {
x = x - 50
} while (y >= 0 && x >= 0 );
You don't close off your "do" loop - you just go right into the while after the else. In order for your code to work properly, you need to insert a bracket after the else:
let x = 100
let y = 100
do {
//...
if (random == 1) {
y = y - 50
} else {
x = x - 50
}
} while (y >= 0 && x >= 0 );

Javascript Maze Runner on Codewars error

I've working my way through codewars, and I've come across mazerunner (https://www.codewars.com/kata/maze-runner/train/javascript) I've been stumped for about 2 days!
function mazeRunner(maze, directions) {
//find start value
var x = 0; //x position of the start point
var y = 0; //y position of the start point
for (var j = 0 ; j < maze.length ; j++){
if (maze[j].indexOf(2) != -1){
x = j;
y = maze[j].indexOf(2)
}
} // end of starting position forloop
console.log(x + ', ' + y)
for (var turn = 0 ; turn < directions.length ; turn++){
if (directions[turn] == "N"){
x -= 1;
}
if (directions[turn] == "S"){
x += 1;
}
if (directions[turn] == "E"){
y += 1;
}
if (directions[turn] == "W"){
y -= 1;
}
if (maze[x][y] === 1){
return 'Dead';
}else if (maze[x][y] === 3){
return 'Finish';
}
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
}
return 'Lost';
}
When I run this, it works on most of the scenarios, however on the last one I get the following error
TypeError: Cannot read property '3' of undefined
at mazeRunner
at /home/codewarrior/index.js:87:19
at /home/codewarrior/index.js:155:5
at Object.handleError
Any help would be appreciated! I'm pulling my hair out over this one!
The problem of your solution is that after the move, you just check the value of maze[x][y]
In the test that fails, maze[x] will be at some point undefined (moves south for a while). I guess at that same point y would be 3, hence the error Cannot read property '3' of undefined
To avoid that, you should move up the code where you test for undefined, before trying to access the coordinates:
// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}

Javascript Else If switch using HTML input. Checking a value and displaying a result accordingly. Cost Estimator

I am making a simple cost estimator. I want to make an else if switch that checks the imputed values and displays a certain string dependant on those values. The cost estimation is working but I cant get the Else If switch to function.
Here is my codepen: http://codepen.io/FredHair/pen/FgJAd
I have tried to have a go here:
function myContainer(){
var container;
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
if (z < 25 && x < 110 && y < 90 ){
container = "1";
}
else if (z < 25 && x < 110 && y < 180 ){
container = "2";
}
else if (z < 25 && x < 220 && y < 90 ){
container = "3";
}
else if (z < 50 && x < 110 && y < 90 ){
container = "4";
}
else if (z < 50 && x < 110 && y < 180 ){
container = "5";
}
else if (z < 50 && x < 220 && y < 90 ){
container = "6";
}
else if (z < 75 && x < 110 && y < 90 ){
container = "7";
}
else if (z < 75 && x < 110 && y < 180 ){
container = "8";
}
else if (z < 75 && x < 220 && y < 90 ){
container = "9";
}
else if (z < 100 && x < 110 && y < 90 ){
container = "10";
}
else if (z < 100 && x < 110 && y < 180 ){
container = "11";
}
else if (z < 100 && x < 220 && y < 90 ){
container = "12";
}
else{
container = "?"
}
document.getElementById("container").innerHTML = container;
}
This is obviously meant to display a value in the HTML h3 id= "container", but currently nothing happens.
Where am I going wrong? is there a much better way to set up this? Using JQuery perhaps? Any help will be greatly appreciated. Sorry for my basic coding.
Your myContainer function is never being called. If you were to add it to your other function after you display the results, you'd get the results you wanted. Such as:
...
//Display Result//
document.getElementById("result").innerHTML = " = £ " + result;
myContainer();
}
That said you could simplify both functions. For example, the switch statement doesn't really serve much of a purpose, since you can modify your markup to produce the results that you want by changing your values to 50 and 30 such as:
<select id="choice" >
<option value = "1">1</option>
<option value = "50">2</option>
<option value = "30">3</option>
</select>
Now in your calculator function, you can set the result with a ternary operator. You read it like an if statement, meaning (if the value is true) ? (do this) : (else do this).
function calculator(){
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
var choice = Number(document.getElementById("choice").value);
var result = (choice === 1) ? z * 3 : x * 3 + choice;
//Display Result//
document.getElementById("result").innerHTML = " = £ " + result;
myContainer(x,y,z); //pass the values of x, y, z as arguments
}
You could simplify your myContainer as well, by passing the values to it for x, y and z directly from the calculator function, then you don't need to go back to the DOM and retrieve those values again.
function myContainer(x, y, z){
var container;
//all your if-else here ..
document.getElementById("container").innerHTML = container;
}

Categories