How can I identify the quarter from the value in a jQuery datepicker?

Viewed 92

I have an input field text which is readonly. I'm using it to display the year quarter. I have another input field which is a start date. I'm using jQuery datepicker for choosing the date.

My problem is that the quarter input field value Q1 then if I choose a start date outside of Q1 I need to display a message below it saying:

The selected start date is not within the quarter

How can I do that?

var datePickerOptions = {
  dateFormat: 'dd-M-yy',
  changeMonth: true,
  changeYear: true
}

/* Initialise the date picker */
if (!$.datepicker.initialized) {
  $(document).mousedown($.datepicker._checkExternalClick)
    .find(document.body).append($.datepicker.dpDiv);
  $.datepicker.initialized = true;
}

$(function() {
  $("#startdate").datepicker(datePickerOptions);
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Quartor: <input type="text" id="quartor" readonly value="Q1"></p>
<p>Start Date: <input type="text" id="startdate" placeholder="DD-MMM-YYYY"></p>

1 Answers

To achieve this you can hook to the onSelect() method of the datepicker. There you can execute code which uses a simple calculation to determine the quarter of year from the selected date, and compare it to the value entered by the user, something like this:

let getQuarter = d => Math.ceil((d.getMonth() + 1) / 3);
let datePickerOptions = {
  dateFormat: 'dd-M-yy',
  changeMonth: true,
  changeYear: true,
  onSelect: dateValue => {
    let date = new Date(dateValue);
    let dateQtr = 'Q' + getQuarter(date);
    let userQtr = $('#quartor').val().trim();
    $('.qtr-warning').toggle(dateQtr != userQtr);
  }
}

jQuery($ => {
  $("#startdate").datepicker(datePickerOptions);
});
.qtr-warning {
  color: #C00;
  display: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Quartor: <input type="text" id="quartor" readonly value="Q1"></p>
<p>Start Date: <input type="text" id="startdate" placeholder="DD-MMM-YYYY"></p>
<span class="qtr-warning">The selected start date is not within the quarter</span>

Note that you may wish to make the comparison more robust by making it case-insensitive, or ignoring the Q string.

Related