Is there a way to change cases within the switch statement? - javascript

So, I'm working on a switch statement and i was wondering if it's possible to change the case on a specific action.
Lets say I have this:
var check0 = false;
var check1 = false;
switch(stage){
case "0":
rect(10,10,10,10);
check0 = true;
break;
case "1":
if(check0 === true){
rect(20,20,20,20);
check1 = true;
break;
}else{
/* How to set case 0 ? */
//stage = 0; //Doesnt work
//stage = "0"; //Doesn't work
}
break;
}

var check0 = false;
var check1 = false;
function xyz(stage){
switch(stage){
case "0":
rect(10,10,10,10);
check0 = true;
break;
case "1":
if(check0 === true){
rect(20,20,20,20);
check1 = true;
break;
}else{
xyz(0)
}
break;
}
}

Wrap in function:
var check0 = false;
var check1 = false;
function checkFunc(stage) {
switch(stage){
case "0":
rect(10,10,10,10);
check0 = true;
break;
case "1":
if(check0 === true){
rect(20,20,20,20);
check1 = true;
break;
}else{
checkFunc("0")
}
break;
}
}
checkFunc("1");

Your options for this are to use the method #Tarun Khurana and #Artee have suggested or reorganize the cases so case "1" is on top of case "0", but only breaks if the condition is met:
switch(stage){
case "1":
if(check0 === true){
rect(20,20,20,20);
check1 = true;
break;
}
// case "0" is executed since there is no break statement
case "0":
rect(10,10,10,10);
check0 = true;
break;
}

Try this:
var check0 = false, check1 = false;
function checkSet(stage){
switch(stage){
case 0:
//rect(10,10,10,10);
check0 = true;
return;
case 1:
if(check0 === true){
//rect(20,20,20,20);
check1 = true;
return;
}
else{
checkSet(0);
}
return;
}
}
console.log(check0); checkSet(1); console.log(check0);

Related

Submit form via AJAX using plain Javascript without Jquery get checked radio button value

I do have HTML form submitting via AJAX using plain Javascript:
function XMLhttp(){
var formInputs = document.getElementById(formID).querySelectorAll("input, textarea");
var selectFormGebdat = formID;
var toCheckDatesFields = document.getElementsByClassName("checkDate");
for (var i = 0; i < toCheckDatesFields.length; i++) {
if(toCheckDatesFields.item(i).value != '') {
var returnValue = validatedate(toCheckDatesFields.item(i));
if(returnValue == false) {
return false;
}
}
}
var httpRequest = new XMLHttpRequest();
var formData = new FormData();
for( var i=0; i < formInputs.length; i++ ){
formData.append(formInputs[i].name, formInputs[i].value);
}
httpRequest.onreadystatechange = function(){
if ( this.readyState == 4 && this.status == 200 ) {
resultData = JSON.parse(this.responseText);
if(resultData.success == true) {
document.getElementById('resultok').className += ' show';
}
else {
document.getElementById('resulterror').className += ' show';
};
}
};
httpRequest.open(formMethod, formAction);
httpRequest.send(formData);
}
selectButton.onclick = function(){
XMLhttp();
}
selectForm.onsubmit = function(){
return false;
}
My problem is, that I have radio buttons and select-box. But the selected values are not submitted. F.ex.
<input type="radio" name="typ" value="anfrage"><input type="radio" name="typ" value="reservierung">
If anfrage is checked, the script is not submitting this value - there is always reservierung submitting.
Thanks for help!
Martin
I could solve this by:
var formData = new FormData();
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
formData.append(form.elements[i].name, form.elements[i].value);
}
break;
case 'file':
break;
}
break;
case 'TEXTAREA':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
formData.append(form.elements[i].name, form.elements[i].value);
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
formData.append(form.elements[i].name, form.elements[i].value);
break;
}
break;
}
}

Case in Switch statement involving array with conditions

I have an array which is to be iterated and depending on the condition execute task
I have done this with if else and trying it out with Switch.And the condition is if (1 && 2) (then execute A) else if (1) (then execute B) else if (2) (then execute c) else if (none) (then execute D)
function showFiletRelateddata(selectedFilter) {
/*if (selectedFilter.length === 0) {
console.log("No data");
} else if (
selectedFilter.includes("Request") &&
selectedFilter.includes("Reservation")
) {
console.log("RequestReservation");
} else if (selectedFilter.includes("Request")) {
console.log("Request");
} else if (selectedFilter.includes("Reservation")) {
console.log("Reservation");
}*/
var filt = selectedFilter;
for (var i = 0; i < filt.length; i++) {
var supp = filt[i];
switch (supp) {
case "Request":
case "Reservation":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
}
The if else is working fine however what correction needs to be made for Switch statement
For ref =
Javascript switch case with array or strings
function showFiletRelateddata(selectedFilter) {
var filt = selectedFilter;
var supp = ""
for (var i = 0; i < filt.length; i++) { //loop over length of array
supp = supp + filt[i]; // concat elements of array
}
switch (supp) {
case "RequestReservation": // if case contains one of the condition
case "ReservationRequest":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
var a = ["Reservation", "Request"];
var b = ["Request","Reservation"];
var c = ["Reservation"];
var d = ["Request"];
showFiletRelateddata(a);
showFiletRelateddata(b);
showFiletRelateddata(c);
showFiletRelateddata(d);

How to write if ,else block for multiple conditions?

I am new to javascript what is right way to write if and else block with below code i am getting an error on else condition that syntax is not correct. Please let me know what i have implemented wrong.
main.js
if (dataRow.opriskYesNo === 'Yes') {
$scope.opRiskCompleted = 'Y';
} else if (dataRow.opriskYesNo === 'No') {
$scope.opRiskCompleted = 'N';
} else(dataRow.opriskYesNo === '') {
$scope.opRiskCompleted = '';
$scope.opRiskCompleted = '';
}
You should have else without any condition in your last conditional code block.
Though the improved version would look like below, I'd say maintain one object with key value and use it.
var mappedModel = {'Yes': 'Y', 'No': 'N'};
$scope.opRiskCompleted = mappedModel[dataRow.opriskYesNo] || '';
Why don't you use a Switch?
switch(dataRow.opriskYesNo){
case "Yes":
$scope.opRiskCompleted = 'Y';
break;
case "No":
$scope.opRiskCompleted = 'N';
break;
default:
$scope.opRiskCompleted = '';
break; }
Try this:
if(dataRow.opriskYesNo==='Yes'){
$scope.opRiskCompleted = 'Y';
} else if (dataRow.opriskYesNo==='No') {
$scope.opRiskCompleted = 'N';
} else {
$scope.opRiskCompleted = '';
$scope.opRiskCompleted = '';
}

Call a function with its parameters if all required keys are pressed

I am trying to create a function that will call another function (passed as a parameter) if all the required keys are pressed. This is what I have so far:
function multiKeyPress(funcName, parms, key0, key1, key2, key3, key4, key5) {
var down = [];
var noKeys = arguments.length - 2
var args = parms
// for (i = 0; i < noKeys; i++) {
// if (i == noKeys - 1) {
// keyPress += ('down[key' + i + '])')
// } else {
// keyPress += ('down[key' + i + '] && ')
// }
// }
console.log(noKeys)
console.log(args);
switch (noKeys) {
case 1:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 2:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 3:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 4:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 5:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3] && down[key4]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 6:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3] && down[key4] && down[key5]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
}
}
Near the top of the function I have commented out a loop that would create a string with the necessary keys but I couldnt pass that as a condition because a string will be a truthy value. Therefore I resorted to a long switch statement. This currently works but I was wondering if there was a way to clean it up or if there are any potential problems.
Thanks
You're on the right track, you just need to think about using arrays.
function multiKeyPress(funcName, parms) {
var keysPressed = Array.prototype.slice.call(arguments, 2);
var down = [];
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
var allPressed = keysPressed.every(function (key) {
return down[key];
});
if (allPressed) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
}
That gets any number of keys passed into the function by treating the arguments like an array. Then the keyup handler uses the every method of Array to make sure all of the entries in the array have been pressed.
I should warn you I haven't tested this in a working application, since none was provided, but I'm pretty sure it will function as a replacement.
If you want help with sorting out this string you talk about in the question, do include it in the question, or add a new question specifically about that code.

Javascript: Assigning keys to Two Different Objects on One Canvas

I want to put two different colored rectangles on one canvas and assign different keyboard keys to use each separately . Unfortunately it only works for one of them. Here is my code. I added different variables for each object, but still the other one doesn't appear. Should I apply something to the function or with the window.onload?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var GAME_SPEED = 1000/60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
window.onload = function()
{
c = document.getElementById("myCanvas");
c.width = window.innerWidth*0.9;
c.height = window.innerHeight*0.9;
window.setInterval("draw()" , GAME_SPEED);
}
document.onkeyup = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =false;
break;
case 39: rightKey = false;
break;
case 38: upKey = false;
break;
case 40: downKey = false;
break;
case 32: spaceKey = false;
break;
case 65: aKey =false;
break;
case 83: sKey = false;
break;
case 68: dKey = false;
break;
case 87: wKey = false;
break;
case 13: enterKey = false;
break;
}
}
document.onkeydown = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =true;
break;
case 39: rightKey = true;
break;
case 38: upKey = true;
break;
case 40: downKey = true;
break;
case 32: spaceKey = true;
break;
case 65: aKey =true;
break;
case 83: sKey = true;
break;
case 68: dKey = true;
break;
case 87: wKey = true;
break;
case 13: enterKey = true;
break;
}
}
function draw()
{
if(leftKey == true)
{
x--;
}
if(rightKey == true)
{
x++;
}
if(upKey == true)
{
y--;
}
if(downKey == true)
{
y++;
}
if(spaceKey == true)
{
sideLength++;
}
var c = document.getElementById("myCanvas");
var cntxt = c.getContext("2d");
cntxt.fillStyle= "#FF0000";
cntxt.fillRect(x, y, sideLength, sideLength);
}
function draw2()
{
if(aKey == true)
{
bX--;
}
if(dKey == true)
{
bX++;
}
if(wKey == true)
{
bY--;
}
if(sKey == true)
{
bY++;
}
if(enterKey == true)
{
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = b.getContewxt("2d");
cntxt2.fillStyle= "#F00000";
cntxt2.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
</script>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid
#000000;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
You have a number of problems in your code. The first is that you were never calling the draw2 function. The second is that you were trying to use two different contexts. It is best to use only one global context.
The fixed code is below.
var GAME_SPEED = 1000 / 60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
var ctx;
window.onload = function() {
c = document.getElementById("myCanvas");
c.width = window.innerWidth * 0.9;
c.height = window.innerHeight * 0.9;
ctx = c.getContext('2d');
window.setInterval(function() {
draw();
draw2();
}, GAME_SPEED);
}
document.onkeyup = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = false;
break;
case 39:
rightKey = false;
break;
case 38:
upKey = false;
break;
case 40:
downKey = false;
break;
case 32:
spaceKey = false;
break;
case 65:
aKey = false;
break;
case 83:
sKey = false;
break;
case 68:
dKey = false;
break;
case 87:
wKey = false;
break;
case 13:
enterKey = false;
break;
}
}
document.onkeydown = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = true;
break;
case 39:
rightKey = true;
break;
case 38:
upKey = true;
break;
case 40:
downKey = true;
break;
case 32:
spaceKey = true;
break;
case 65:
aKey = true;
break;
case 83:
sKey = true;
break;
case 68:
dKey = true;
break;
case 87:
wKey = true;
break;
case 13:
enterKey = true;
break;
}
}
function draw() {
if (leftKey == true) {
x--;
}
if (rightKey == true) {
x++;
}
if (upKey == true) {
y--;
}
if (downKey == true) {
y++;
}
if (spaceKey == true) {
sideLength++;
}
ctx.fillStyle = "#FF0000";
ctx.fillRect(x, y, sideLength, sideLength);
}
function draw2() {
if (aKey == true) {
bX--;
}
if (dKey == true) {
bX++;
}
if (wKey == true) {
bY--;
}
if (sKey == true) {
bY++;
}
if (enterKey == true) {
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = ctx;
ctx.fillStyle = "#F00000";
ctx.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid
#000000;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
Here's to solve your problem and some tips:
Move the drawing of your 2nd player into draw()
You don't have to declare new canvas-variables for your 2nd player, just use the ones you had
If you want to keep some of your old code, fix the typo where you declare the context a second time var cntxt2 = b.getContewxt("2d");
function draw() {
if(leftKey == true) {
x--;
}
if(rightKey == true) {
x++;
}
if(upKey == true) {
y--;
}
if(downKey == true) {
y++;
}
if(spaceKey == true) {
sideLength++;
}
var c = document.getElementById("myCanvas");
var cntxt = c.getContext("2d");
cntxt.fillStyle= "#FF0000";
cntxt.fillRect(x, y, sideLength, sideLength);
if(aKey == true) {
bX--;
}
if(dKey == true) {
bX++;
}
if(wKey == true) {
bY--;
}
if(sKey == true) {
bY++;
}
if(enterKey == true) {
sideLengthZ++;
}
cntxt.fillStyle= "#F00000";
cntxt.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}

Categories

Resources