Search code examples
javascriptjqueryjquery-uidatepicker

How to get date when selecting year and month in datepicker


Is there a way to automatically get the date when the year and month are selected without clicking the done button?

$(function() {
  $('.date-picker, .to').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    onClose: function(dateText, inst) {
      $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
      $('#to').datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth + 1, 0));
    }
  });
});
.ui-datepicker-calendar {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<label for="startDate">Year/Month :</label>
<input name="startDate" id="startDate" class="date-picker" />
<input name="startDate" id="to" class="to" />


Solution

  • Consider the following example.

    $(function() {
      function setDate(target, year, month, string) {
        var myDate;
        if ($(target).is("#first")) {
          day = 1;
          myDate = $.datepicker.parseDate("yy-mm-dd", year + "-" + month + "-01");
        } else {
          myDate = new Date(year, month, 0);
        }
        if (string) {
          $(target).val($.datepicker.formatDate("yy-mm-dd", myDate));
        } else {
          $(target).datepicker("setDate", myDate);
        }
      }
    
      $('.date-picker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy-mm-dd',
        onChangeMonthYear: function(yy, mm) {
          setDate(this, yy, mm, true);
        },
        onClose: function(dateText, inst) {
          if ($(this).is("#first")) {
            setDate("#last", inst.selectedYear, inst.selectedMonth + 1, true);
          }
        }
      });
    });
    .ui-datepicker-calendar {
      display: none;
    }
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <label for="startDate">Year/Month :</label>
    <input id="first" class="date-picker" />
    <input id="last" class="date-picker" />

    If the User changes the Month and Year they want, yet then clicks away, this will populate the field, in the same you were doing in onClose.