How do you compare today's date with the date provided by Django using JavaScript/JQuery?

Viewed 77

The whole problem is to compare the date extracted from the database and passed to the input field in the template with today's date generated by jquery.

Unfortunately when I tried print startDt console return me "undefined value"

$(document).ready(function() {
  let endDt = new Date();

  $(".date").each(function() {
    let startDt= $(this).attr('data-book').val;
    if ((new Date(startDt).getTime() < new Date(endDt).getTime())) {
      // Rest of code here
    }
  });
});
<input type="date" class="date" hidden data-book="{{ book.slug }}" value="{{ book.date|date:" Y-m-d " }}">

1 Answers

Your logic is almost there. The issue is with the way you're retrieving the attributes from the element.

To fill the startDt variable you need to invoke the val() method (including parentheses). attr('data-book') is not required (and if it was it should be data('book') instead).

Try this:

jQuery($ => {
  let endDt = new Date();

  $(".date").each(function() {
    let startDt = $(this).val();
    if ((new Date(startDt).getTime() < new Date(endDt).getTime())) {
      console.log('start is BEFORE end');
    } else {
      console.log('start is AFTER end');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" class="date" hidden data-book="{{ book.slug }}" value="2020-03-18">
<input type="date" class="date" hidden data-book="{{ book.slug }}" value="2018-03-18">
<input type="date" class="date" hidden data-book="{{ book.slug }}" value="2050-03-18">

Related