Wednesday, February 22, 2012

Using jquery datepicker (calendar)

jquery datepicker is very easy to implement. We can have it in action on text-field or on calendar image icon click. All we need to do is -

Add jquery library, jquery UI library and jquery UI CSS
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!--[jQuery Library]-->
    <script src="jquery-ui-1.8.9.custom.min.js"></script> <!--[jQuery UI Library]-->  
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />

When you have these three files in the HEAD section of your HTML file, you can write the jquery calendar code -

<script type="text/javascript">
$(function(){
   
$('.showCalendarTextFieldClass').datepicker({
    minDate: new Date(2012, 0, 1),
    maxDate: new Date(2012, 1, 26),
    dateFormat: 'dd/mm/yy',
    selectMultiple:true,
    showOn: 'button',
    //showOn: 'both',
    buttonImage: 'img/calendarIcon.png',
    buttonImageOnly: true   
});

//   
});
</script>

The code below shows how you can change calendar icon on mouseover  and restore it back on mouseout or when clicked outside of calendar/datepicker, and add alternate text to the icon on mouseover -

//jquery datepicker mouseover/hover change icon
    $(".ui-datepicker-trigger, .ui-datepicker").mouseover(function() {
        $('.ui-datepicker-trigger').css('cursor', 'pointer').attr({alt: 'Pick Date', title: 'Pick Date', src: 'img/calendarIconActive.png'});       
        if($('.ui-datepicker').css("display") == "block"){
            $('.ui-datepicker-trigger').attr({src: 'img/calendarIconActive.png'});
        }
    }).mouseout(function(){
        $('.ui-datepicker-trigger').attr({src: 'img/calendarIcon.png'});
        if($('.ui-datepicker').css("display") == "block"){
            $('.ui-datepicker-trigger').attr({src: 'img/calendarIconActive.png'});
        }       
    });
    $('.ui-datepicker').click(function(e) {
        e.stopPropagation();
    });
    $(document).click(function() {
        $('.ui-datepicker-trigger').attr({src: 'img/calendarIcon.png'});
    });


<input type="text" class="showCalendarTextFieldClass" />

You are done!

More options, events, methods, theming is here - http://jqueryui.com/demos/datepicker/