Question

I need implement a Jquery UI Calendar that when a users click any date, it select automatically to the next MOM or EOM.

For example, if the user clicks on April 9th, it must go to 'April 15th', or if clicks on 22 February, it must go to 'Feb 28' or 'Feb 29'.

For clarification: MOM is "Middle of Month, every time is 15th", from 1 to 15 of any month. EOM is "End of Month, it's the last day of the month, jan 31, feb 28 or 29, mar 31, apr 30, may 31, jun 30, july 31, aug 31, sep 30, oct 31, nov 30, dec 31...

Thanks

Was it helpful?

Solution 3

The code that works with IE6/IE7/IE8/IE9 and FF, Chrome, etc.

    <script type="text/javascript">
    $(function() {
        $("#payperiodcalendar input").datepicker({
            dateFormat: 'dd-M-yy',
            onSelect: function(dateText, inst) {
                var selectedDay = inst.currentDay,
                selectedMonth = inst.currentMonth,
                selectedYear = inst.currentYear;



                if (selectedDay <= 15) {
                    var now = new Date(selectedYear, selectedMonth, 15);
                } else {
                    var now = new Date(selectedYear, selectedMonth, LastDayOfMonth(selectedYear, selectedMonth));
                }
                $(this).attr("value", now.format("dd-MMM-yyyy"));

            }
        });
        function LastDayOfMonth(Year, Month) {
            Month++;
            return (new Date((new Date(Year, Month, 1)) - 1)).getDate();
        }
    });



</script>

OTHER TIPS

I would do this as a standard jquery onchange handler for the text box. The reason is that a user can bypass the date-picker and type in a date manually. You want the date to automatically be changed no matter if the date is selected, typed in, or pasted in.

Use the onSelect event from datepicker. Be aware that if you have maxDate option set and its before EOM or MOM the value selected will be maxDate.

UPDATE: Close after select. Use onClose instead.

UPDATE2: jsFiddle using latest jQuery UI

  onClose: function(dateText, inst) {
    var day = inst.currentDay,
        month = inst.currentMonth,
        year = inst.currentYear;

    if (day <= 15) {
      day = 15;
    }
    else {
      day = 0;
      if (month>10){
        month = 0;
        year++;
      }
      else
        month++;
    }
    var d = new Date(year, month, day);
    $(this).datepicker("setDate", d);
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top