Search code examples
jquerydatejs

jquery: iterate through tables comparing <td>hardcoded date</td> against Date.today() then dropping dates<today


Thanks to all for considering my newbe issue. I'm using jQuery to iterate through a table and capture all hardcoded dates in an array. I compare those dates against Date.today(); using .isAfter() function. If hardcoded date is in the past, it should get a .css("display", "none");

<table>
    <html>
      <table>
        <tr class="gig">

           <td class="gigDate">Mar 27 2013</td>
           <td>the Saloon</td>
           <td>Atlanta, Ga</td>
           <td>$20 (2 passes)</td>
            <td>button to purchase tix<td>
        </tr>

        <tr class="gig"><td class="gigDate"> ... date2 ..</td></tr>
        <tr class="gig"><td class="gigDate"> ... date3 ..</td></tr>
        <tr class="gig"><td class="gigDate"> ... date4 ect ..</td></tr>
  </table>

<script type="text/javascript">
$("document").ready( function() {

var stringDate = []; //create array to hold elements

var now = Date.today(); // create current date

$('.gigDate').each(function (i, e) {   //adds hardcoded dates to array
stringDate.push($(e).text());
});

for(var y = 0; y < stringDate.length; y++){
var singleDate =  Date.parse(stringDate[y]);  //parse to milliseconds
var compare = now.isAfter(singleDate);        //compare to today's date

if(compare){
    $('.gig').css("display", "none");   //hide <tr class="gig"> 
                                      //if in the past
      }
}    
 });
</script>

Loop logic seems to function properly, but the if(statement) that adds style display:none is whack. Any help would be greatly appreciated.


Solution

  • When you try to hide a single row, you just hide all of them - $('.gig') selects all rows, not just the one you think it should.

    Move your logic inside the loop where you test the date. Roughly like this (I'm changing your code as little as possible, might still not work, haven't checked):

    var now = Date.today(); // create current date
    
    $('.gigDate').each(function (i, e) {   //adds hardcoded dates to array
       var current = ($(e).text());
       var singleDate =  Date.parse(current);  //parse to milliseconds
       var compare = now.isAfter(singleDate);        //compare to today's date
       if(compare){
           // we want to hide the parent of td, not the td:
           $(e).parent().css("display", "none");   //hide <tr class="gig"> 
                                          //if in the past
       }
    
    });