I'm doing a switch statement in javascript:
switch($tp_type){ case 'ITP': $('#indv_tp_id').val(data); break; case 'CRP'||'COO'||'FOU': $('#jurd_tp_id').val(data); break; }
But I think it doesn't work if I use OR operator. How do I properly do this in javascript? If I choose ITP,I get ITP. But if I choose either COO, FOU OR CRP I always get the first one which is CRP. Please help, thanks!
switch expression can't be float, double or boolean.
The JavaScript switch case is a multiple if else statement. It takes a conditional expression just like an if statement but can have many conditions—or cases—that can match the result of the expression to run different blocks of code.
The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.
The expression in the switch can be a variable or an expression - but it must be an integer or a character. You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other. The optional default case is executed when none of the cases above match.
You should re-write it like this:
case 'CRP': case 'COO': case 'FOU': $('#jurd_tp_id').val(data); break;
You can see it documented in the switch
reference. The behavior of consecutive case
statements without break
s in between (called "fall-through") is described there:
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.
As for why your version only works for the first item (CRP
), it's simply because the expression 'CRP'||'COO'||'FOU'
evaluates to 'CRP'
(since non-empty strings evaluate to true
in Boolean context). So that case
statement is equivalent to just case 'CRP':
once evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With