I’m encountering an issue with my switch statement in JavaScript where it only processes the first case and skips the rest, even though I placed break statements correctly throughout.
I aim to compare today’s date with some specific dates in a dropdown menu. If any of those dates are earlier than today, I want to hide and disable those options. While I successfully employed if-else statements for this task, I thought a switch statement could offer a better performance.
Here’s my code:
var firstDate = new Date();
firstDate.setFullYear(2023, 2, 15);
var secondDate = new Date();
secondDate.setFullYear(2023, 2, 28);
var thirdDate = new Date();
thirdDate.setFullYear(2023, 3, 10);
var fourthDate = new Date();
fourthDate.setFullYear(2023, 3, 25);
var fifthDate = new Date();
fifthDate.setFullYear(2023, 4, 8);
var currentDate = new Date();
var dropdown = document.getElementById("DateSelector");
switch (true) {
case firstDate < currentDate:
for (var j = 0; j < dropdown.length; j++)
var option = dropdown.options[1];
option.style.display = "none";
option.disabled = true;
break;
case secondDate < currentDate:
for (var j = 0; j < dropdown.length; j++)
var option = dropdown.options[2];
option.style.display = "none";
option.disabled = true;
break;
case thirdDate < currentDate:
for (var j = 0; j < dropdown.length; j++)
var option = dropdown.options[3];
option.style.display = "none";
option.disabled = true;
break;
case fourthDate < currentDate:
for (var j = 0; j < dropdown.length; j++)
var option = dropdown.options[4];
option.style.display = "none";
option.disabled = true;
break;
case fifthDate < currentDate:
for (var j = 0; j < dropdown.length; j++)
var option = dropdown.options[5];
option.style.display = "none";
option.disabled = true;
break;
}
What could be the reason only the first case executes? I appreciate any suggestions!