demo demo - 5 months ago 7
Javascript Question

Js switch by 2 variables always execute first case

I have 2 variables :

var1
and
var2
.

I found this answer http://stackoverflow.com/a/9235320/3917754 I try to implement it in my case :

switch (var1 | var2) {
case ('Contact' | true):
$('#btnCopyCompanyAddress').removeClass('hidden');
$('#btnCopyPersonalAddress').addClass('hidden');
break;
case ('Company' | true):
$('#btnCopyCompanyAddress').addClass('hidden');
$('#btnCopyPersonalAddress').removeClass('hidden');
break;

default:
$('#btnCopyCompanyAddress, #btnCopyPersonalAddress').addClass('hidden');
}


but always first case is executed even if
var1
=
Company
and
var2
=
true
.

Answer

You can use "+" instead of "|" :

function Check(var1, var2) {
    switch (var1 + var2) {
    case ('Contact' + var2):
        alert('1');
        break;
    case ('Company' + var2):
        alert('2');
        break;
    default:
        alert('0');
 }
}
Comments