So I’m trying to do a switch – case based on months. If a user picks 1 then it prints january.. I have all the months in a array so arr[0] = January but the picking 1 in the dropdown would print "january". In my code I keep getting the wrong month, it’s always one behind. I’ve read some documentation on the switch – case but I think I’ve misunderstood the "expression". I’m trying to use case switch to avoid having a bunch of if-statements.
function months() {
monthText = document.getElementById("month");
var monthNumber = document.getElementById("month_number").value;
var monthsArr = ["January", "February", "March", "April", "May", "June", "July", "August", "September", " October", "November", "December"];
switch (monthNumber) {
//Januari
case monthNumber == "1":
monthText = monthsArr[0];
break;
//Februari
case monthNumber == "2":
monthText = monthsArr[1];
break;
//Mars
case monthNumber == "3":
monthText = monthsArr[2];
break;
//April
case monthNumber == "4":
monthText = monthsArr[3];
break;
//Maj
case monthNumber == "5":
monthText = monthsArr[4]
break;
//Juni
case monthNumber == "6":
monthText = monthsArr[5];
break;
//Juli
case monthNumber == "7":
monthText = monthsArr[6];
break;
//Augusti
case monthNumber == "8":
monthText = monthsArr[7];
break;
//Septembar
case monthNumber == "9":
monthText = monthsArr[8];
break;
//Oktober
case monthNumber == "10":
monthText = monthsArr[9];
break;
//November
case monthNumber == "11":
monthText = monthsArr[10];
break;
//December
case monthNumber == "12":
monthText = monthsArr[11];
break;
}
monthText.value = monthsArr[monthNumber];
console.log(monthsArr[monthNumber]);
}
<form>
<form>
<fieldset>
<select id="month_number" onchange="months()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<input type="text" id="month" value="" size="15" />
>Solution :
You seem to be using it in wrong way.
In switch part the month number should go and in case part you should not be comparing like you are doing. The correct code would be something like:
switch (monthNumber) {
//January
case 1:
monthText = monthsArr[0];
break;
// February
case 2:
monthText = monthsArr[1];
break;
// ... so on
}
You can see a similar example here: https://www.w3schools.com/js/js_switch.asp
Also note that this problem can be solved in better ways as well. Eg:
monthText = monthsArr[monthNumber - 1];
/* Let's say user selects 1, so this statement would evaluate monthNumber -
1 first which would be 1 - 1 = 0 and returns monthsArr[0] which is actually January.*/