magna_nz
magna_nz

Reputation: 1273

output not displaying javascript

Using javascript, for some reason I can't output "Tuesday" by the function even though d.getDay() is 2.

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
    if (day == 1){
        return "Monday";
    else if (day == 2){
        return "Tuesday";
    else{
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>
</html>

Upvotes: 0

Views: 49

Answers (3)

Alberto Acu&#241;a
Alberto Acu&#241;a

Reputation: 535

The problem to solve this is so easy, you just forget close your 'if', and 'else if' using this => '}'

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
if (day == 1){
    return "Monday";
}else if (day == 2){
    return "Tuesday";
}else{
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>

Upvotes: 0

angelcool.net
angelcool.net

Reputation: 2546

Check your curly brackets. Working version:

JSFiddle

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
    if (day == 1)
    {
        return "Monday";
     }
    else if (day == 2)
    {
        return "Tuesday";
    }
    else
    {
        return "Otherday";
     }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>
</html>

Upvotes: 3

Matt
Matt

Reputation: 276

It looks like you're missing the closing curly braces on your else statements. I've updated your snippet below.

function getDayOfWeek(day){
    if (day == 1) {
        return "Monday";
    } else if (day == 2) {
        return "Tuesday";
    } else {
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());

Upvotes: 4

Related Questions