I'm trying to simplify some information on my play-site.
There are two dif. user-types, students and others.
Many places and stores offer a discount to students, and I would therefore make this accessible with a checkbox that changes some of the scripts.
This Is my example (simplifyed as good as i could):
<head>
<script TYPE="text/javascript" SRC="script/script_uteplasser.js"></script>
</head>
<body>
<form action="">
<input type="checkbox" id="checkbox_student" onclick="student();"><span>I'm A student!</span></input></form>
(...)
</body>
javascript (script_uteplasser):
//--------------------SAMFUNDET---------------------
samfundet = "...blablablabla..." + cc_samfundet() + "...blablablabla...";
//----INNGANGSAV. SAMFUNDET----
var checkbox1 = document.getElementById("checkbox_student");
function student(){
if (checkbox1.checked){
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "Free"; break; case 2: return "Free"; break; case 3: return "Free"; break; case 4: return "Free"; break; case 5: return "Free"; break; case 6: return "Free"; break; case 0: return "Free";}}
}
else{
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "100,-"; break; case 2: return "100,-"; break; case 3: return "100,-"; break; case 4: return "100,-"; break; case 5: return "100,-"; break; case 6: return "100,-"; break; case 0: return "100,-";}}
}
}
//-------------------------------------------------
This doesn't kill the script, but isn't returning any information either.
Why do you want to redefine function ?
You can check in your function if checkbox is checked. If you want really to redefine function use this code :
//declare your function :
function cc_samfundet () {
//...
}
//or :
var cc_samfundet2 = function () { /* ... */ };
//redefine your function :
cc_samfundet = function () {
//...
}
//or with an existing function :
cc_samfundet = cc_samfundet2;
It doesn't return anything because you're only defining your function(s) in your evaluation. If you add a second pair of parentheses afterwards, it should work how you intend.
That said, this is a really poor design pattern. First of you don't really need to make what you're doing functions here. Second is creating the same named function twice with completely separate logic - that pretty much brakes every good programming principle.
Update: Here is something to point you in the right direction,
var checkbox1 = document.getElementById("checkbox_student");
// Assuming this function should do something else too?
function student() {
cc_samfundet(checkbox1.checked);
}
var cc_samfundet = function (isStudent) {
var d = new Date();
var theDay = d.getDay();
switch (theDay) {
case 1:
return isStudent ? "Free" : "100,-";
// and so on
}
}
Related
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.
all. I'm fairly new to JavaScript - currently trying to understand the switch statement. I'm having a problem understanding how I still got a return value when I did no assignments to my result variable. The switch statement is nested in a function.
function caseInSwitch(val) {
let result = "";
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
return result;
}
caseInSwitch(1);
I expect result to be an empty string "", but it shows the following value immediately... without any assignments...!
You're returning in the switch statement. In the case where val equals 1, the switch statement never gets past case 1. The function doesn't return result, it executes return "alpha".
That return statement terminates the function:
function caseInSwitch(val) {
console.log("1: function start. Val:", val);
let result = "";
console.log("2: before switch");
switch(val) {
case 1:
console.log("3: before return alpha");
return "alpha";
console.log("4: after return alpha");
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
console.log("5: after switch");
return result;
}
var finalResult = caseInSwitch(1);
console.log("Final result:", finalResult);
As you can see, only statements 1-3 get logged.
The return statement in the switch also means the breaks are redundant:
switch(val) {
case 1:
return "alpha";
case 2:
return "beta";
case 3:
return "gamma";
case 4:
return "delta";
}
Those break statements are only necessary to terminate the case, if you're not returning out of the case:
let variable = "";
switch(val) {
case 1:
variable = "alpha";
break;
case 2:
variable = "beta";
break;
case 3:
variable = "gamma";
break;
case 4:
variable = "delta";
break;
}
console.log(variable);
The answer is pretty simple, you are passing 1 as the value for val in caseInSwitch. In the switch block, 1 is matched with case 1 and the function returns alpha. Keep in mind the return in the switch block, makes the control return from the function itself and not just from the switch block
This is my example program in JS. I have to iterate or loop inside the switch statement. So I have used goto, but it doesn't working.
Are there any other options to loop this or is my syntax wrong?
var input = 1;
switch (input)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
if (..) { }
else
{
goto case 2;
}
break;
default:
alert("No Return");
break;
}
Are there any possibilities to use "goto" inside switch statement in javascript?
No, there are no possibilities to use "goto" inside switch statement, or anywhere else, since JavaScript has no such statement.
To solve your problem, as suggested in a comment, organize your cases (moving 3 above 2) so you can use fall-through:
var input = 1;
switch (input)
{
case 1:
...
break;
case 3:
...
if (..) { ...; break; }
// fall through to case 2
case 2:
...
break;
default:
alert("No Return");
break;
}
In this case, make sure to comment the fall-through so people looking at your code don't think it's a bug. You may also need to add a hint so that your linter does not complain.
Or, just put the logic common to 2 and 3 in a little function:
function someLogicFor2Or3() { ... }
case 2:
someLogicFor2OrMaybe3();
break;
case 3:
...
if (..) { }
else someLogicFor2OrMaybe3();
break;
I have used the following technique to do this :
var input = 1;
while (1) {
switch (input) {
case 1:
...
break; // switch
case 2:
...
break; // switch
case 3:
...
if (..) { }
else {
input = 2; // goto case 2;
continue; // while
}
break; // switch
default:
alert ("No Return");
break; // switch
}
break; // while
}
I'm attempting an exercise and can't quite understand where I'm going wrong.
I have a form where my postcode field will only validate if it meets the requirements of the regex specific to the state chosen.
I need to use a switch statement to determine what RegEx to use based on the state choice.
This is what I have so far:
function validPostCode() {
var state = (document.getElementById("state").value);
switch (state) {
case "SA":
var stateRegEx = /^5([0-9]{3})$/;
break;
case "NSW":
var stateRegEx = /^2([0-9]{3})$/;
break;
}
return stateRegEx.test(document.getElementById("postcode").value);
}
Try this:
function validPostCode() {
var state = (document.getElementById("state").value);
var stateRegEx; // added here
switch (state) {
case "SA":
stateRegEx = /^5([0-9]{3})$/; // var removed
break;
case "NSW":
stateRegEx = /^2([0-9]{3})$/; // var removed
break;
}
return stateRegEx.test(document.getElementById("postcode").value);
}
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'