Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Calculate Date

Any reason why this is landing on the wrong day?

http://jsfiddle.net/SparrwHawk/MH5wP/

I've written the code below for reference, but it's obviously clearer on jsfiddle

<p>Sun / Closed</p>
<p>Mon / Closed</p>
<p>Tues / 9am – 5pm</p>
<p>Wed / 9am – 5pm</p>
<p>Thurs / 9am – 8pm</p>
<p>Fri / 9.30pm – 6.30pm</p>
<p>Sat / 8.30am – 4.30pm</p>

<script>
// Day where 0 is Sunday
var date = new Date();
var d = (date.getDay());

$(function(){
    if (d = 1) {
        $('p:contains("Mon")').addClass('today');
    } else if (d = 2) {
        $('p:contains("Tues")').addClass('today');
    } else if (d = 3) {
        $('p:contains("Wed")').addClass('today');
    } else if (d = 4) {
        $('p:contains("Thurs")').addClass('today');
    } else if (d = 5) {
        $('p:contains("Fri")').addClass('today');
    } else if (d = 6) {
        $('p:contains("Sat")').addClass('today');
    } else {
        $('p:contains("Sun")').addClass('today');
    }    
});
</script>
like image 596
SparrwHawk Avatar asked Dec 28 '25 06:12

SparrwHawk


2 Answers

You gotta use double equal signs (==) to check your value of d, otherwise you'll set d=1 with your first if statement and you'll always have a red Monday.

like image 67
Tomm Avatar answered Dec 30 '25 21:12

Tomm


You are using assignement (=) instead of comparison (== or ===) in your if.

So what you are doing is if ( (d = 1) === true ) aka if if you can assign 1 to d. This works, so the code enters your first if and the elses are never touched.

A simple way to make sure not to do that sort of mistake is to reverse the order of the operands when checking against hardcoded values:

$(function(){
  if (1 == d) {
    // do something ...

This way if you mistakenly use =, the assignation fails and you get an error.

like image 34
Lepidosteus Avatar answered Dec 30 '25 21:12

Lepidosteus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!