lundi 7 janvier 2019

Looping through each "If statement" in a jQuery function

I wrote four functions to check to see if the current date is before or after a specific date (date1, date2, date3, date4). Originally, I tried to write this in one function but it would break out of the function after the first "if" statement because it was true. In my coding example below, it would show the div with ID 19700101-p but not the div with ID 20180501-p (because as I understand it, since the current date was greater than date1, the "if" statement was true and there was no need to execute the "else if" statements after it.

For greater context, I have a page of 19 courses with registration buttons. My goal is to write a script that will automatically "disable" the registration button when the date has passed. Additionally it will show some additional information (i.e., "This class has passed, the next class will take place on xxx").

Is there a simpler way to write this function?

$(document).ready(function() {

  var current = new Date();
  var date1 = new Date("January 1, 1970")


  if (current.getTime() > date1.getTime()) {
    $('#19700101-f').hide();
    $('#19700101-p').show();
  }
  $('#currentDate').html(current);
  $('#date1').html(date1);
});

$(document).ready(function() {

  var current = new Date();
  var date2 = new Date("May 1, 2018")


  if (current.getTime() > date2.getTime()) {
    $('#20180501-f').hide();
    $('#20180501-p').show();
  }
  $('#date2').html(date2);
});

$(document).ready(function() {

  var current = new Date();
  var date3 = new Date("January 7, 2019")

  if (current.getTime() > date3.getTime()) {
    $('#20190107-f').hide();
    $('#20190107-p').show();
  }
  $('#date3').html(date3);
});

$(document).ready(function() {

  var current = new Date();
  var date4 = new Date("May 1, 2019")

  if (current.getTime() > date4.getTime()) {
    $('#20190501-f').hide();
    $('#20190501-p').show();
  }
  $('#date4').html(date4);
});

Aucun commentaire:

Enregistrer un commentaire