Javascript switch statement using regular expressions - javascript

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);
}

Related

Why is my switch case not working in JavaScript?

I want the variable CurrectcoinValue will get the value of the correct case, but it's not working.
const CurrectcoinValue = "null";
const symbol = "usdt";
casim(symbol, CurrectcoinValue);
console.log("result : " + CurrectcoinValue);
function casim(symbol, CurrectcoinValue) {
switch (symbol) {
case "btc":
CurrectcoinValue = "BTC";
break;
case "eth":
CurrectcoinValue = "ETH";
break;
case "usdt":
CurrectcoinValue = "USDT";
break;
case "usdc":
CurrectcoinValue = "USDC";
break;
default:
CurrectcoinValue = 1;
}
}
There are 2 fundamental problems with your solution:
If you want to be able to change a variable, you need to declare it with let or var (preferably let because the scope is tighter). const is used when explicitly you don't want a variable to be changed.
You can't set a string variable from within a function, JS won't change that variable since it doesn't keep a reference to it!
Also, i think that we have a better way to treat this, which is using a function that does not change any parameter reference, only calculating the value:
const symbol = "usdt";
const CurrectcoinValue = casim(symbol);
console.log("result : " + result);
function casim(symbol) {
switch (symbol) {
case "btc":
return "BTC";
case "eth":
return "ETH";
case "usdt":
return "USDT";
case "usdc":
return "USDC";
default:
return 1;
}
}
This way you are not battling with reference issues.
You could also take the advice of using the symbol.toUpperCase(); method for the cases that are not the default, that would save some code repetition :)

Using AddEventListener to change variable to 'True' using a Switch statement [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 2 years ago.
I'm building a calculator in HTML, CSS & Javascript. When a user clicks a number it is added to an Array. Which Array it is added to is determined by three variables which are initially set to false. If the variable is true then that Array has already been used.
The problem I am facing is that my event listener for the operands is failing to change the value of the three variables to true when required to do so.
Initial Variables
var numberArrayOne = [];
var numberArrayTwo = [];
var numberArrayThree = [];
var operandOne = false;
var operandTwo = false;
var operandThree = false;
This is the code that listens for operand clicks.
const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
switch(false){
case (operandOne):
var operandOne = true;
break;
case (operandTwo):
var operandTwo = true;
break;
case (operandThree):
var operandThree = true;
break;
default:
console.log("Error");
}
});
This code chooses which array to place a number into.
const displayFunction = (num) => {
switch(true){
case (!operandOne):
numberArrayOne.push(num);
console.log(numberArrayOne);
break;
case (!operandTwo):
numberArrayTwo.push(num);
console.log(numberArrayTwo);
break;
case (!operandThree):
numberArrayThree.push(num);
break;
default:
}
};
Clicking divide button on my calc the value remains false, it should change to true, and I am getting the console.log(error) message I added as the default.
I was declaring a variable in only the function scope. Removing VAR has resolved
const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
switch(false){
case (operandOne):
operandOne = true;
break;
case (operandTwo):
operandTwo = true;
break;
case (operandThree):
operandThree = true;
break;
default:
console.log("Error");
}
});

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 and jQuery hasClass function

I am trying to use a switch statement to check if the current page has a specific body class. This is kind of what I am looking for:
var bodyClass = $('body').hasClass('className')
switch(bodyClass) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
I do understand that the jQuery hasClass function returns true of false and is used like $('body').hasClass('someClassName') and this will return true or false. Also, my body typically has about 7-10 different class names for a given page.
This is not the use case for a switch in my opinion, but a simple set of branches
var body = $('body');
if(body.hasClass('abc')) {
}
else if(body.hasClass('def')) {
}
else {
/* default case */
}
/* etc */
I agree with the other answer that you're better suited to just use if, else if statements here, but an alternative would be to rip the classes off the body tag and check them against your strings:
var bodyClasses = ($('body').attr('class') || '').split(' ');
for (var i = 0, len = bodyClasses.length; i < len; i++) {
switch(bodyClasses[i]) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
}
I know this is an old thread, but it may help someone else.
If you are able to ensure the classes for the element are declared in a specific order, you could ensure the class you are checking for is first / last in the list, and use something similar to this:
var bodyClass = $('body').attr('class');
var firstClass = bodyClass.slice(0, bodyClass.indexOf(' '));
switch(firstClass) {
case 'homepage':
// Some code here
break;
case 'residential-page':
// Other code here
break;
default:
// More code here
}

switch between functions with checkboxes?

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
}
}

Categories

Resources