jQuery Datepicker with Simple Example



jQuery Date-picker most commonly used date-picker today in web applications. In this article I am explaining how to use jQuery Datepicker and it’s utility function with simple example. For example we need to save an event which has two dates `from` and `to`. So we need two date-picker fields and on the selection of `from` date, we need to disable all before dates in the `to` date-picker UI.

So we have the following form to get the date.

    <label for="from">From</label>
    <input id="from" type="text" name="from" />
    <label for="to">to</label>
    <input id="to" type="text" name="to" />

Now to set a date-picker we need to add script like as below. We can change date format using dateFormat: “yy-mm-dd” and enable month change by changeMonth: true and set a minimum date by minDate: new Date().

$( "#from" ).datepicker({
    dateFormat: "yy-mm-dd",
    changeMonth: true
});

Now we will take the same date-picker script for the field ‘to’ as above. Now we need to disable all the dates before selected date in ‘from’ field. So we need to add following script to the ‘from’ date-picker script as below.

$( "#from" ).datepicker({
    dateFormat: "yy-mm-dd",
    changeMonth: true,
    onSelect: function(dateText, inst) {
        var selectedDate = $( this ).datepicker( "getDate" );
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
    }
});

Date-Picker ‘onSelect’ function fire on the date selection in ‘from’ field and set the minDate in ‘to’ date-picker. So we need to add the same for `to` field as below to set a max date for `from` field on date selection.

$( "#to" ).datepicker({
    dateFormat: "yy-mm-dd",
    changeMonth: true,
    onSelect: function(dateText, inst) {
        var selectedDate = $( this ).datepicker( "getDate" );
	$( "#from" ).datepicker( "option", "maxDate", selectedDate );
    }
});

If you want to select a date range with jQuery datepicker here is a simple example.

LIVE DEMO

jQuery Datepicker with Simple Example
jQuery Datepicker with Simple Example