Trying to use nested switch commands to generate correct outputs on specific fields. In this specific example, the heading value of basement, main floor or 2nd floor of a house depends on the number of house floors. I tried 2 different scripts but none of them has provided any output.
//1st script:
switch (this.getField("Floor Location").value) {
case "-":
event.value = "-";
break;
case "B":
switch ((this.getField("Storeys").value)) {
case "-":
event.value = "-";
break;
case "One Storey":
event.value = "11";
break;
case "Two Storeys":
event.value = "17";
break;
}
case 'M':
switch (this.getField("Storeys").value) {
case "-":
event.value = "-";
break;
case "One Storey":
event.value = "1";
break;
case "Two Storeys":
event.value = "11";
break;
}
case "2nd":
switch (this.getField("Storeys").value) {
case "-":
event.value = "-";
break;
case "One Storey":
event.value = "_";
break;
case "Two Storeys":
event.value = "1";
break;
}
default:
event.value = this.getField("Floor Location").value;
break;
}
// No output
//2nd script:
var TwoStoreys = storeys;
var floor = this.getField("Floor Location").value;
if (floor = "-");
var none = floor;
var storeys = this.getField("Storeys").value;
if (storeys = "-");
var zero = storeys;
if (storeys = "One storey");
var OneStorey = storeys;
if (storeys = "Two Storeys");
var TwoStoreys = storeys;
var floor = this.getField("Floor Location").value;
if (floor = "-");
var none = floor;
if (floor = "B");
var B = floor
if (floor = "M");
var M = floor
if (floor = "2nd");
var Second = floor;
switch (true) {
case ((zero) && (none)):
event.value = "-";
break;
case ((zero) && (B)):
event.value = "-";
break;
case ((zero) && (M)):
event.value = "-";
break;
case ((zero) && (Second)):
event.value = "-";
break;
case ((Onestorey) && (none)):
event.value = "-";
break;
case ((Onestorey) && (B)):
event.value = "11";
break;
case ((Onestorey) && (M)):
event.value = "1";
break;
case ((Onestorey) && (Second)):
event.value = "-";
break;
case ((Twostoreys) && (none)):
event.value = "-";
break;
case ((Twostoreys) && (B)):
event.value = "17";
case ((Twostoreys) && (M)):
event.value = "11";
break;
case ((Twostoreys) && (Second)):
event.value = "1";
break;
}
2
Answers
1 – First Script
The lack of break statements:
2 – Second Script
The use of
=
instead of===
on the second script while using conditional statements was the major error, so you only need to change this, but I made this for you:Other recommendations:
1 – Group all declarations at the top of your code.
2 – Avoid duplicate variable declarations.
3 – Use === instead of == for comparison to avoid unintended type coercion.
4 – Provide a default value in your switch statement.
I’d use an object to map between the values and forgo
switch
altogether:Note: I use optional chaining so I don’t have to worry about whether a floor location is defined. I could also remove the
"-"
entries too, since everything defaults to "-" anyway.