Clare-Backstage
Clare-Backstage

Reputation: 31

Javascript redirect based on date

I want the user to be directed to bar.html on the first of the month, gjb.html on the second of the month, guerr.html on the third of the month and error.html on other dates.

What am I doing wrong? The following only loads bar.html regardless of the date on the user's computer.

<html>
<script type="text/javascript">
    currentTime = new Date();
    if (currentTime.getDate() = 1)
        window.location = "bar.html";
    else if (currentTime.getDate() = 2))
        window.location = "gjb.html";
    else if (currentTime.getDate() = 3))
        window.location = "guerr.html";
    else window.location = "error.html";
</script>
</html>

I'm brand new to all this, so explain it like you would to a total idiot.

Upvotes: 3

Views: 1472

Answers (3)

baielybelle
baielybelle

Reputation: 11

try using double equals (==). The single equals operator signifies assignment while the double equals signifies a comparison.

Example:

// Assign a value to a int a = 1;

// Assign a value to b int b = 2;

// See whether or not a is equal to b

if( a == b ) {
        System.out.println("They're equal!");
}
else {
         System.out.println("They're not equal!");
} 

Upvotes: 1

jhamm
jhamm

Reputation: 25032

You are setting the date with currentTime.getDate() = 1. Try currentTime.getDate() == 1 or currentTime.getDate() === 1. (I dont use js all the time, but '=' is wrong).

Upvotes: 1

BeRecursive
BeRecursive

Reputation: 6376

Just needs to be a proper equality check, not the assignment operator you are using:

<html>
<script type="text/javascript">
    var currentDate = new Date().getDate();
    if (currentDate === 1)
        window.location = "bar.html";
    else if (currentDate === 2))
        window.location = "gjb.html";
    else if (currentDate === 3))
        window.location = "guerr.html";
    else window.location = "error.html";
</script>
</html>

I suggest === over == because that does a proper type check, and you are guaranteed to get Integers so this is a safer check. When in doubt, ===.

Upvotes: 3

Related Questions