views:

42

answers:

2

At the top of my script I have created a variable out of todays date:

<?php $today = date('dmy'); ?>

I then have a table and each table row has a class either of "nodate" or of a six digit number, this number represents a date. eg 230910 (yesterday).

I am trying to write some jquery that hides the table row if the class (six digits) is less than todays date ($today) as a number. eg if 230910 < 240910

<script type="text/javascript">
    var todaysdate = "<?php echo $today;?>";
    $(document).ready(function() {
        $("#main table tr").each(function() {
            if ($(this).hasClass('nodate')) {
                $(this).css("background", "blue");
                } else {                    
                    var expire = (parseInt($(this).attr('class')));
                    alert (expire);

                    if (expire < todaysdate) {
                    $(this).css("background", "red");
                }
            }
        });

    });
</script>

For testing I have it so if the table row has a class of "nodate" then the background changes blue. Then if table rows date (six digit number) is less than todays date then go red.

Currently all the rows with the six digits are turning red and for some reason, if the digits start with a zero then the class outputs differently.

eg

<tr class="<?php $date = "041010";  echo $date; ?>">

Outputs as 16904 :S

can anyone help?

+5  A: 

A number that starts with a zero is parsed as an octal number (base 8), not as a decimal number (base 10).

Specify the radix (base) when you parse the number:

parseInt($(this).attr('class'), 10)

Also, unless you only have dates within the same month, you should use an ISO 8601 based date format (ymd), e.g. 100924 rather than 240910.

With the date first, you get the effect that for example 250810 > 240910.

Guffa
+1 - Radix is very important. Also, MDC has a nice [ **parseint() reference** ](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt).
Peter Ajtai
perfect, works great now. didnt realise there were so many date formats.
AJFMEDIA
A: 

var todaysdate = "<?php echo $today;?>"; <--- this is a string

var expire = (parseInt($(this).attr('class')));
alert (expire);

expire < todaysdate <-- you are comparing a string to an integer

Diodeus
Javascript should be able to handle such simple type coercion. ==> [ **1** ](http://jsfiddle.net/MfTm4/), [ **2** ](http://jsfiddle.net/5fzZA/) ------- However if **both** are string, they'll be compared alphabetically ==> [ **1** ](http://jsfiddle.net/ANET5/)
Peter Ajtai