Click event: switch statement not working - javascript

I´m trying to trigger multiple click events depending on the var clicked, however the switch statement isn´t working. I think it´s the "var" inside the Switch parameter but I have no idea how to correct it:
var buttonQ = document.getElementById('Heater1button');
var buttonW = document.getElementById('Heater2button');
var buttonE = document.getElementById('Heater3button');
var buttonA = document.getElementById('Heater4button');
var buttonS = document.getElementById('Heater6button');
var buttonD = document.getElementById('OpenHHbutton');
var buttonZ = document.getElementById('KicknHat');
var buttonX = document.getElementById("Kickbutton");
var buttonC = document.getElementById('CClosedHHbutton');
$(document).click(function() {
switch (var) {
case buttonQ:
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case buttonW:
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
case buttonE:
document.getElementById('E').play(), $("#displaytext").text("Heater 3")
break;
case buttonA:
document.getElementById('A').play(), $("#displaytext").text("Heater 4")
break;
case buttonS:
document.getElementById('S').play(), $("#displaytext").text("Heater 6")
break;
case buttonD:
document.getElementById('D').play(), $("#displaytext").text("Open HH")
break;
case buttonZ:
document.getElementById('Z').play(), $("#displaytext").text("KicknHat")
break;
case buttonX:
document.getElementById('X').play(), $("#displaytext").text("Kick")
break;
case buttonC:
document.getElementById('C').play(), $("#displaytext").text("Closed HH")
break;
}
})

You shouldn't use a switch statement, use event listeners attached to each element.
buttonQ.addEventListener("click", function() {
document.getElementById('Q').play(), $("#displaytext").text("Heater 1");
});
buttonW.addEventListener("click", function() {
document.getElementById('W').play(), $("#displaytext").text("Heater 2");
});
and so on for all the buttons.

Something like this?
$(document).click(function(e) {
var id = e.target.id;
switch (id) {
case "Heater1button":
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case "Heater2button":
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
}
});

You're correct, the issue is the var inside the switch statement. What variable does this refer to? A switch statement is used to "check the result of a and do one of x, y, etc". In your example I don't see any declaration of a value called "var" that the switch is using to evaluate what case to run.
In any event, even if you did have a variable somewhere else in your code called var, it won't work because that is a reserved word. You can't name a variable using the word you use to name variables.

You are switching on var, which itself does not appear to exist from the code you have provided. You need to know what was clicked, so you need to use what the jQuery .click() method provides - "this". Or perhaps in your case you should switch on $(this).attr("id").
See this: https://api.jquery.com/click/

Related

Changing style through JavaScript doesn't work with variables

I want to do is change the left margin of a DOM element based on a variable in JavaScript. This function works:
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
document.querySelector('#About-content1').style.marginLeft = "0";
break;
case 1:
document.querySelector('#About-content1').style.marginLeft = "-100%";
break;
case 2:
document.querySelector('#About-content1').style.marginLeft = "-199%";
break;
default:
break;
}
}
This successfully sets the margin-left property like I want it to. However, I don't want to call document.querySelector every time I call the updateTabs function. I tried this:
var contentDiv1 = document.querySelector('#About-content1');
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
However, this only works the first time I call the function. After that, it prints "Switching to tab" but doesn't actually modify the style. Is there any way I could change the style without having to call document.querySelector every time?
I think the reason is that the second time around it doesn't know what contentDiv1 is how about you put that inside the function like this:
function updateTabs(i) {
var contentDiv1 = document.querySelector('#About-content1');
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
So now everytime the function runs it knows what contentDiv1 is. So now you still call document.querySelector only once but the function know what you want.
The question is missing some context, but if Hadi Pawar's answer isn't correct, my guess is that the element is being destroyed and recreated. This should validate that:
var contentDiv1 = document.querySelector('#About-content1');
contentDiv1.myResize = function(i) {
console.log('Switching to tab ' + i)
var offsets = [0, -100, -199];
if( i > offsets.length ) return;
this.style.marginLeft = offsets[i] + '%';
}
[...]
contentDiv1.myResize( n );
Now, when you call resize, you will get a hard error if 'contentDiv1' loses scope. Otherwise, the logic is contained within the element itself.
Turns out that the problem was that I had a Vue.js element connected to the same element, so the element was changed. I moved the Vue.js declaration to before the const contentDiv1 = document.querySelector('#About-content1'), and it fixed the problem.

Switch statement not behaving like it should

so i have a piece of code where i have an array (ar=[1,2,3,4,5]) and two functions. the functions are supposed to do the exact same thing: print out something if 1 exists in the array. but function func is always returning "nope" instead of "one" but function another always return the right thing. the only difference between the two functions is function func have a switch instead of an if/else. why? in the source code there are about 12 cases so i actually need to use the switch.
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (one) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}
function another (num) {
if(num===2){
console.log("found two");
} else if(num===3){
console.log("found thre");
} else{
console.log("nope");
}
}
ar.forEach(func);
ar.forEach(another);
You have to use the value you want to compare to one
hence
case 1:
instead of
case one===1
here's a fiddle
https://jsfiddle.net/cunx1ono/
Easiest way. Change the switch param to true if you want to use a comparison in the case, because one===1 returns true/false. This is why you always get "nope".
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (true) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}

From IF/ELSE to Switch in Javascript

So, I'm trying to substitute the code within the IF statements to run the same way in a Switch statement. However, I can't seem to understand how to get the functions to run the same way in the switch as they do in the if statement. Here's the code I've written with the if statement. Could anyone help me figure out how to format it correctly to run with the switch statement instead?
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
if (i == 5) {
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}
i++;
}
I am not sure why you want the switch but for sample purposes here is how a switch would work for the code you posted above:
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
switch(i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
break;
default:
// any code you want to run in the else statement
}
i++;
}
This switch statement would replace the current if statement that you have.
switch (i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}

unwanted situations after creating button in javascript

I need to create a button dynamically with javascript. so i wrote these codes in between "script" tags.
window.onload = function () {
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'What's the day today?';
newButton.id = 'btn1';
newButton.onclick = myfunction();
div1.appendChild(newButton);
}
function myfunction() {
var x = new Date().getDay();
switch (x) {
case 0: alert("sunday"); break;
case 1: alert("monday"); break;
case 2: alert("tuesday"); break;
case 3: alert("wednesday"); break;
case 4: alert("thursday"); break;
case 5: alert("friday"); break;
case 6: alert("saturday"); break;
}
}
when the page is loaded, "myfunction()" function is running automatically. after that when i press this button, nothing happens. what's my mistake?
You need to change
newButton.onclick = myfunction;
When you do newButton.onclick = myfunction(); it executes the myfunction and then assigns the value returned by it to the onclick handler, in this case undefined. What you need to do is to pass the function reference to the onclick property
Also I assume the following is a copy paste change
newButton.value = 'What's the day today?'; // you need to escape ' with \' or use "What's the day today?"

javascript switch(true)

Hi i am trying to handle an ajax json response
here is my code
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
It works for me:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the case labels must be equal to true, not just implicitly true.
Also, only the first case that evaluates to true will execute.
SOLVED
Based on SLaks answer i modify the code as below
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
Thank to all
You need to read up on the switch statement. You should not be switching on a constant value.
It appears that you need to use if statements, as you don't really want to be switching on your j value:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
In a case like this, a better way to do this is probably something like:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}
Why not use an object literal instead of a switch(true) ?
const j= {
choice1: false,
choice2: true
};
const map = {
true: 'default',
...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']
console.log(map) // 'choice2'

Categories

Resources