Pages

Monday, 24 September 2012

Jquery Date picker to display only month and year or only week



Customization of jquery Datepicker to select date by week,month and year.


          JQuery support nice customization features. In this tutorial we will see how to customize JQuery Date picker to select by week,by month and by year.


1)Select Week :As below image shows that week is highlighted  which allows user to select week. When week is selected it set the Monday's date in input box.

Jquery Date picker to select week only
      To achieve above customization with jquery date picker, use following code :.

Click Here to View Demo


//replace  selectWeek with your date pickers id here at all places
$(function(//this is onload
$("#selectWeek")
      .datepicker(
      {
            firstDay : 1, // set first day of week as monday
            changeMonth : true, // provide option to select Month
            changeYear : true, // provide option to select year
            showButtonPanel : true, // button panel having today and done button
           
        onClose : function(dateText, inst) {
                  if ($(this).val() == "") {
                        return;
                  }
           
                  // below code will calculate the monday and set it in input box
                  var fromDate = $("#selectWeek").datepicker("getDate");
                  var date = fromDate.getDate();
                  var month = fromDate.getMonth() + 1;// +1 as jan is 0
                  var year = $(
                  "#ui-datepicker-div .ui-datepicker-year :selected").val();
     
                  if (fromDate.getDay() != 1) { // if not monday
                        if (fromDate.getDay() == 0) {// if sunday
                              date = date - 6;
                        } else {
                              date = date + (-fromDate.getDay() + 1);
                        }
                  }
                  var dateStr = month + "/" + date + "/" + year;
                  $(this).val(dateStr);
                  $(this).blur();// remove focus input box
        },
            duration : 0,

            onChangeMonthYear : function() {
                  setTimeout("applyWeeklyHighlight()", 100);
                  },// applyWeeklyHighlight is below
                  beforeShow : function() {
                        setTimeout("applyWeeklyHighlight()", 100);
                  }
            });
});//end of onload

/**
 * Set highhlight on the week on hover.
 */
function applyWeeklyHighlight() {

      $('.ui-datepicker-calendar tr').each(function() {

            if ($(this).parent().get(0).tagName == 'TBODY') {
                  $(this).mouseover(function() {
                        $(this).find('a').css({
                              'background' : '#ffffcc',
                              'border' : '1px solid #dddddd'
                        });
                        $(this).find('a').removeClass('ui-state-default');
                        $(this).css('background', '#ffffcc');
                  });
                 
                  $(this).mouseout(function() {
                        $(this).css('background', '#ffffff');
                        $(this).find('a').css('background', '');
                        $(this).find('a').addClass('ui-state-default');
                  });
            }

      });
}



2)Select Month: As below image shows that date grid is hidden and user is allowed to select only month and year.
Jquery Date picker to select month and year only
                                   
      To achieve above customization with jquery date picker, use following code in page onload function.


//replace   selectMonth with your date pickers id here at all places
$('#selectMonth').datepicker( {
    changeMonth: true,      //provide option to select Month
    changeYear: true,       //provide option to select year
    showButtonPanel: true// button panel having today and done button
    dateFormat: 'MM yy',    //set date format
    onClose: function(dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));//here set the date when closing.
            $(this).blur();//remove focus input box
           
    }
});

      //on foucus event on this code is to hide the calender part
$("#selectMonth").focus(function () {
    $(".ui-datepicker-calendar").hide();
    $("#ui-datepicker-div").position({
        my: "center top",
        at: "center bottom",
        of: $(this)
    });
});                



3)Select Year : As below image shows that month and date grid is hidden, user is allowed to select only year .
Jquery Date picker to select year only


      To achieve this customization with jquery date picker ,use following code in  page onload function.


//replace selectYear with your date pickers id here at all places
$('#selectYear').datepicker( {
   
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy',
    onClose: function(dateText, inst) {
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, 1, 1));
        var strDate ="01/01"+"/"+year;
        $(this).blur();//remove focus input box 
    }
});
      //this code is to hide the calendar part of year calendar
      $("#selectYear").focus(function () {
    $(".ui-datepicker-calendar").hide();
    $("#ui-datepicker-div").position({
        my: "center top",
        at: "center bottom",
        of: $(this)
    });
});


To download source code of the example go to below link :

DatePickerCustomization

How to run after download :
1)Extract the zip file.
2)Open DatePickerCustomization.html in browser
3)This file contains whole source code



12 comments:

  1. Hi Vikram,

    I've been using your code to implement a select week function in my application. I found that it is buggy. If you select any of the days in the first week of August, the month column value changes to -2.

    ReplyDelete
    Replies
    1. I noticed that too so I fixed it. Add this code to correct the date (I tested it):

      if (date < 1) {
      month = month - 1;
      if (month == 2) { //February?
      if (year % 4 == 0) { //Leapyear?
      date = 29 + date;
      } else {
      date = 28 + date;
      }
      } else if (month % 2 == 0 && month < 8) { //even and between Jan and Jul
      date = 30 + date;
      } else if (month % 2 == 0 && month > 8) { //even and between Aug and Dec
      date = 31 + date;
      } else if (month % 2 != 0 && month < 8) { //uneven and between Jan and Jul
      date = 31 + date;
      } else if (month % 2 != 0 && month > 8) { //uneven and between Aug und Dec
      date = 30 + date;
      }
      }

      Delete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from javascript and jquery training in chennai .
    or learn thru Javascript Training in Chennai.
    Nowadays JavaScript has tons of job opportunities on various vertical industry. javascript and jquery training in chennai

    ReplyDelete
  3. Wow, nice information like your way of explanation, it can be easily understanding.

    Best Microsoft Training in Bangalore for Microsoft, we provide the Microsoft training project with trainers having more than 5 Years of Microsoft training experience, we also provide 100% placement support.

    ReplyDelete
  4. It was a very good experience,Faculty members are very knowledgeable and cooperative. Specially My trainer teaching more as he focused upon practical rather than theory. All together it was an enlightening and informative course.

    microsoft training and placement support in bangalore

    microsoft training free demo class

    microsoft placement bangalore

    microsoft online training

    microsoft classroom training

    microsoft training with lab facilities

    microsoft training with certified and experienced trainers

    ReplyDelete
  5. I am really thanking you for the great work which you have been did.It is easily understandable.Eagerly waiting for further updates.
    Java training in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Online Training

    ReplyDelete
  6. It was a very good experience,Faculty members are very knowledgeable and cooperative. Specially My trainer teaching more as he focused upon practical rather than theory. All together it was an enlightening and informative course.
    angular js training in chennai

    angular js training in omr

    full stack training in chennai

    full stack training in omr

    php training in chennai

    php training in omr

    photoshop training in chennai

    photoshop training in omr

    ReplyDelete