Wednesday, July 15, 2015

Jquery Example : Open Calendar Datepicker on anchor click event

Following example shows a generic method that will enable adding multiple date picker fields on a page. This example assumes that are multiple date fields on the page hence we pass the id attribute dynamically.

This specific example required three separate input fields for date, month and year respectively.
Example uses JQuery UI 1.9.2 and some external resources :

http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
http://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css

Following structure is required for add a date div:

  <div id="dateDiv" class="dateDiv">
        <input type="text" id="monthField"></input> /
        <input type="text" id="dayField"></input> /
        <input type="text" id="yearField"></input>
        <a id="date1Link" onClick="openCalendar('dateDiv')" class="datepickerlink"><i class='fa fa-calendar' title="select"></i></a>
        <br/><span class="dateFormatStr">(mm/dd/yyyy)</span>
    </div>

This above structure can easily changed to just have one text field if required.

Following javascript method openCalendar() will be invoked  on onclick event of the link:
This method triggers the calendar control and set the values in three text fields for day, month and year respective.

<script>
    function openCalendar(dateDivElement){
        $('#' + dateDivElement).datepicker({
                showOn: "button",
                buttonText: "<i class='fa fa-calendar'></i>",
                showAnim:"",
                defaultDate: '',
                dateFormat: "mm/dd/yy",
                onSelect: function(date, eventField) {
                    //eventField returns the field on which datepicker is applied.
                    var day = $(this).datepicker('getDate').getDate();
                    var month = $(this).datepicker('getDate').getMonth() + 1;
                    var year = $(this).datepicker('getDate').getYear();
                    $('#selectedDate').html(date);
                    $('#' + dateDivElement +  ' #dayField').val(day);
                    $('#' + dateDivElement +  ' #monthField').val(month);
                    $('#' + dateDivElement +  ' #yearField').val(year);
                    $('#' + dateDivElement +  ' .ui-datepicker').hide();
                }
        });
    }
</script>

A working example of this can be seen in jsfiddle http://jsfiddle.net/sanjayingole/4s8vdmwm/1/

Please note this example dynamically passes the id of the current div in openCalendar() method due but this this can be more easier if there is only one date field on the page, in that case you can simply hard code the name of the input field id in jquery selector. Please refer to the following example for the same http://sanjayingole.blogspot.com/2015/07/an-example-to-add-calendar-control.html

No comments:

Post a Comment