Question

I am trying to get the current month and then put the month inside a div.

function checkmaand()
{
var datum = new Date();
var maand = datum.getMonth();
switch (maand)
{   
    case 0: document.getElementById("maand").innerHTML = "Januari";
    case 1: document.getElementById("maand").innerHTML = "Februari";
    case 2: document.getElementById("maand").innerHTML = "Maart";
    case 3: document.getElementById("maand").innerHTML = "April";
    case 4: document.getElementById("maand").innerHTML = "Mei";
    case 5: document.getElementById("maand").innerHTML = "Juni";
    case 6: document.getElementById("maand").innerHTML = "Juli";
    case 7: document.getElementById("maand").innerHTML = "Augustus";
    case 8: document.getElementById("maand").innerHTML = "September";
    case 9: document.getElementById("maand").innerHTML = "Oktober";
    case 10: document.getElementById("maand").innerHTML = "November";
    case 11: document.getElementById("maand").innerHTML = "December";
}
}

But for some reason the output is December (it is nov right now for the people in the future)

So my question is why does it do that and how can i fix it?

one more thing: I have to make it with javascript.

Was it helpful?

Solution 4

switch (expr) {
  case "Oranges":
    document.write("Oranges are $0.59 a pound.<br>");
    break;
  case "Apples":
    document.write("Apples are $0.32 a pound.<br>");
    break;

In the example of HC_ .

The break is optional but as the explanation will show :

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.

OTHER TIPS

You have to add a break; at the end of every case so that it doesn't continue to the next one.

function checkmaand()
{
var datum = new Date();
var maand = datum.getMonth();
switch (maand)
{   
    case 0: document.getElementById("maand").innerHTML = "Januari";
        break;
    case 1: document.getElementById("maand").innerHTML = "Februari";
        break;
   ...
}
}

and so on

You're missing the "break" at the end of each case.

As others have mentioned, the problem is because you forgot to add a break; at the end of each of your case statements.

As a suggestion, you can simplify your code like this:

function checkmaand() {
    document.getElementById("maand").innerHTML = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date().getMonth()];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top