[RESOLVED]How to validate (disable the dates) a calendar control in javascript

Hi Friends,

I have 2 textboxes to enter the FromDate and ToDate and i use calendar control using Javascript. I cant use the Ajax as our server is old version and it doesnt support Ajax.

Below is the client side part for the txtboxes.

<asp:TextBox ID="txtFromDate" runat="server" onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

<asp:TextBox ID="txtToDate" runat="server" onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

After selecting the From Date from the calendar control, when i try to select the To Date, Only the dates after the from date should be enabled. The dates before From Date should be disabled. Is there any way to do that? Some one please help me.

Below is the code for the Calendar control.

function positionInfo(object) {

var p_elm = object;

this.getElementLeft = getElementLeft;
function getElementLeft() {
var x = 0;
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
while (elm != null) {
x+= elm.offsetLeft;
elm = elm.offsetParent;
}
return parseInt(x);
}

this.getElementWidth = getElementWidth;
function getElementWidth(){
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
return parseInt(elm.offsetWidth);
}

this.getElementRight = getElementRight;
function getElementRight(){
return getElementLeft(p_elm) + getElementWidth(p_elm);
}

this.getElementTop = getElementTop;
function getElementTop() {
var y = 0;
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
while (elm != null) {
y+= elm.offsetTop;
elm = elm.offsetParent;
}
return parseInt(y);
}

this.getElementHeight = getElementHeight;
function getElementHeight(){
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
return parseInt(elm.offsetHeight);
}

this.getElementBottom = getElementBottom;
function getElementBottom(){
return getElementTop(p_elm) + getElementHeight(p_elm);
}
}

function CalendarControl() {

var calendarId = ‘CalendarControl’;
var currentYear = 0;
var currentMonth = 0;
var currentDay = 0;

var selectedYear = 0;
var selectedMonth = 0;
var selectedDay = 0;

var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var dateField = null;

function getProperty(p_property){
var p_elm = calendarId;
var elm = null;

if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
if (elm != null){
if(elm.style){
elm = elm.style;
if(elm[p_property]){
return elm[p_property];
} else {
return null;
}
} else {
return null;
}
}
}

function setElementProperty(p_property, p_value, p_elmId){
var p_elm = p_elmId;
var elm = null;

if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
if((elm != null) && (elm.style != null)){
elm = elm.style;
elm[ p_property ] = p_value;
}
}

function setProperty(p_property, p_value) {
setElementProperty(p_property, p_value, calendarId);
}

function getDaysInMonth(year, month) {
return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
}

function getDayOfWeek(year, month, day) {
var date = new Date(year,month-1,day)
return date.getDay();
}

this.clearDate = clearDate;
function clearDate() {
dateField.value = ”;
hide();
}

this.setDate = setDate;
function setDate(year, month, day) {
if (dateField) {
if (month < 10) {month = "0" + month;}
if (day < 10) {day = "0" + day;}

var dateString = month+"/"+day+"/"+year;
dateField.value = dateString;
hide();
}
return;
}

this.changeMonth = changeMonth;
function changeMonth(change) {
currentMonth += change;
currentDay = 0;
if(currentMonth > 12) {
currentMonth = 1;
currentYear++;
} else if(currentMonth < 1) {
currentMonth = 12;
currentYear–;
}

calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable();
}

this.changeYear = changeYear;
function changeYear(change) {
currentYear += change;
currentDay = 0;
calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable();
}

function getCurrentYear() {
var year = new Date().getYear();
if(year < 1900) year += 1900;
return year;
}

function getCurrentMonth() {
return new Date().getMonth() + 1;
}

function getCurrentDay() {
return new Date().getDate();
}

function calendarDrawTable() {

var dayOfMonth = 1;
var validDay = 0;
var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
var daysInMonth = getDaysInMonth(currentYear, currentMonth);
var css_class = null; //CSS class for each day

var table = "<table cellspacing=’0′ cellpadding=’0′ border=’0′>";
table = table + "<tr class=’header’>";
table = table + " <td colspan=’2′ class=’previous’><a href=’javascript:changeCalendarControlMonth(-1);’>&lt;</a> </td>";
table = table + " <td colspan=’3′ class=’title’>" + months[currentMonth-1] + "<br><a href=’javascript:changeCalendarControlYear(-1);’><font color=’white’ size=’3′>&laquo; </font></a>" + currentYear + "<a href=’javascript:changeCalendarControlYear(1);’><font
color=’white’ size=’3′> &raquo;</font></a></td>";
table = table + " <td colspan=’2′ class=’next’> <a href=’javascript:changeCalendarControlMonth(1);’>&gt;</a></td>";
table = table + "</tr>";
table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

for(var week=0; week < 6; week++) {
table = table + "<tr>";
for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
if(week == 0 && startDayOfWeek == dayOfWeek) {
validDay = 1;
} else if (validDay == 1 && dayOfMonth > daysInMonth) {
validDay = 0;
}

if(validDay) {
if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
css_class = ‘current’;
} else if (dayOfWeek == 5 || dayOfWeek == 6) {
css_class = ‘weekend’;
} else {
css_class = ‘weekday’;
}

table = table + "<td><a class=’"+css_class+"’ href="javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")">"+dayOfMonth+"</a></td>";
dayOfMonth++;
} else {
table = table + "<td class=’empty’>&nbsp;</td>";
}
}
table = table + "</tr>";
}

table = table + "<tr class=’header’><th colspan=’7′ style=’padding: 3px;’><a href=’javascript:clearCalendarControl();’>Clear</a> | <a href=’javascript:hideCalendarControl();’>Close</a></td></tr>";
table = table + "</table>";

return table;
}

this.show = show;
function show(field) {
can_hide = 0;

// If the calendar is visible and associated with
// this field do not do anything.
if (dateField == field) {
return;
} else {
dateField = field;
}

if(dateField) {
try {
var dateString = new String(dateField.value);
var dateParts = dateString.split("-");

selectedMonth = parseInt(dateParts[0],10);
selectedDay = parseInt(dateParts[1],10);
selectedYear = parseInt(dateParts[2],10);
} catch(e) {}
}

if (!(selectedYear && selectedMonth && selectedDay)) {
selectedMonth = getCurrentMonth();
selectedDay = getCurrentDay();
selectedYear = getCurrentYear();
}

currentMonth = selectedMonth;
currentDay = selectedDay;
currentYear = selectedYear;

if(document.getElementById){

calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

setProperty(‘display’, ‘block’);

var fieldPos = new positionInfo(dateField);
var calendarPos = new positionInfo(calendarId);

var x = fieldPos.getElementLeft();
var y = fieldPos.getElementBottom();

setProperty(‘left’, x + "px");
setProperty(‘top’, y + "px");

if (document.all) {
setElementProperty(‘display’, ‘block’, ‘CalendarControlIFrame’);
setElementProperty(‘left’, x + "px", ‘CalendarControlIFrame’);
setElementProperty(‘top’, y + "px", ‘CalendarControlIFrame’);
setElementProperty(‘width’, calendarPos.getElementWidth() + "px", ‘CalendarControlIFrame’);
setElementProperty(‘height’, calendarPos.getElementHeight() + "px", ‘CalendarControlIFrame’);
}
}
}

this.hide = hide;
function hide() {
if(dateField) {
setProperty(‘display’, ‘none’);
setElementProperty(‘display’, ‘none’, ‘CalendarControlIFrame’);
dateField = null;
}
}

this.visible = visible;
function visible() {
return dateField
}

this.can_hide = can_hide;
var can_hide = 0;
}

var calendarControl = new CalendarControl();

function showCalendarControl(textField) {
// textField.onblur = hideCalendarControl;
calendarControl.show(textField);
}

function clearCalendarControl() {
calendarControl.clearDate();
}

function hideCalendarControl() {
if (calendarControl.visible()) {
calendarControl.hide();
}
}

function setCalendarControlDate(year, month, day) {
calendarControl.setDate(year, month, day);
}

function changeCalendarControlYear(change) {
calendarControl.changeYear(change);
}

function changeCalendarControlMonth(change) {
calendarControl.changeMonth(change);
}

document.write("<iframe id=’CalendarControlIFrame’ src=’javascript:false;’ frameBorder=’0′ scrolling=’no’></iframe>");
document.write("<div id=’CalendarControl’></div>");

Thanks.

Hi sinjumujeeb,

I suggest you use the jquery time picker and mention the minDate and maxDate attributes in the datepicker control .

Use the following code:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
    $(function () {
        $("#FromDateDatepicker").datepicker();
    });
    function disablePreviousDates()
    {
        var selectedFromDate = document.getElementById('FromDateDatepicker').value;
        $("#ToDateDatepicker").datepicker({
            minDate: new Date(selectedFromDate),
            maxDate: new Date(2014, 12, 31)
            
        });
    }
</script>
</head>
<body>
<p>From Date: <input type="text" id="FromDateDatepicker" onchange="disablePreviousDates()" /></p>
    <p>To Date:<input type="text" id="ToDateDatepicker" /></p>
</body>
</html>

Working Demo

Hope it helps.

Hi Friend,

Thanks a lot for your reply. This is working fine for me. But what i actually need is when i enter the From Date, My To Date should be enabled till next month, ie, 31 days more than the from date. Above 31 days, it should be disabled. So entering a maximum
Date in the code wont work for me. How can i do this. Can you please help again.

Thanks.

Hi sinjumujeeb,

Thanks for your post.

As for your problem, you could use  Datepicker to select the date range.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="../../../CSS/jquery-ui.css" rel="stylesheet" />
    <script src="../../../Scripts/jquery-1.8.2.js"></script>
    <script src="../../../Scripts/jquery-ui.js"></script>
    <script>
        $(function () {

            $("#from").datepicker({

                defaultDate: "+1w",

                changeMonth: true,

                numberOfMonths: 1,

                onClose: function (selectedDate) {

                    $("#to").datepicker("option", "minDate", selectedDate);

                }

            });

            $("#to").datepicker({

                defaultDate: "+1w",

                changeMonth: true,

                numberOfMonths: 1,

                onClose: function (selectedDate) {

                    $("#from").datepicker("option", "maxDate", selectedDate);

                }

            });

        });


    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <label for="from">From</label>

            <input type="text" id="from" name="from" />

            <label for="to">to</label>

            <input type="text" id="to" name="to" />
        </div>
    </form>
</body>
</html> 

You could check the following link to get more about how to select the date range.

Hope it will be helpful to you.

Best Regards,

Fei Han

Dear Friend,

Thanks for the reply. But my issue is still not solved. What i need is when i select the Fromdate as 2nd Nov, only the Nov month calendar should be enabled for selecting the ToDate. Even if i select 15th Nov as FromDate, the ToDate can be selected only from
the Nov month. So the month for Fromdate and Todate should be the same. Please help me how to do this.

Thanks.

Hi sinjumujeeb,

Try the following code:

function disablePreviousDates()
    {
        var arrayForMonthsHaving31Days=[1,3,5,7,8,10,12];
        var arrayForMonthshaving30Days=[4,6,9,11];
        var selectedFromDate = document.getElementById('FromDateDatepicker').value;
        var dateSelected = new Date(selectedFromDate);
        var month = dateSelected.getMonth();
        var year = dateSelected.getYear();
        var days;
        month++;
        for (var i = 0; i < 7; ++i)
        {
            if (month == arrayForMonthsHaving31Days[i]) days = 31;
            else if (month == arrayForMonthshaving30Days[i] && i < 4) days = 30;
        }
        if (days != 31 && days != 30 && (year%100)%4!=0) days = 28;
        $("#ToDateDatepicker").datepicker({
            minDate: new Date(dateSelected),
            maxDate: new Date(year, month-1, days)
            
        });
        
    }

after you select the first date.

Dear Friend,

Thanks a lot!!! Your code is working fine for me. Now when i enter the FromDate as November 2nd,Only the November calendar is visible for
selecting the Todate. But another issue what is happening is if i reselct the FromDate with another date from another month, The ToDate
calendar is not getting changed accordingly. The calendar for ToDate still shows the old one, according to the Last FromDate which i changed.
Can u show me how to refresh the new entered From Date. Below is your combined code.

<!doctype html>
<html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Datepicker - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <script> $(function () { $("#FromDateDatepicker").datepicker(); });
function disablePreviousDates()
    {
        var arrayForMonthsHaving31Days=[1,3,5,7,8,10,12];
        var arrayForMonthshaving30Days=[4,6,9,11];
        var selectedFromDate = document.getElementById('FromDateDatepicker').value;
        var dateSelected = new Date(selectedFromDate);
        var month = dateSelected.getMonth();
        var year = dateSelected.getYear();
        var days;
        month++;
        for (var i = 0; i < 7; ++i)
        {
            if (month == arrayForMonthsHaving31Days[i]) days = 31;
            else if (month == arrayForMonthshaving30Days[i] && i < 4) days = 30;
        }
        if (days != 31 && days != 30 && (year%100)%4!=0) days = 28;
        $("#ToDateDatepicker").datepicker({
            minDate: new Date(dateSelected),
            maxDate: new Date(year, month-1, days)
            
        });
        
    }
 </script> </head> <body> <p>From Date: <input type="text" id="FromDateDatepicker" onchange="disablePreviousDates()" /></p> <p>To Date:<input type="text" id="ToDateDatepicker" /></p> </body> </html>

1 more doubt is when i use the above HTML textboxes, i can see the calendar and select it. But when i use my ASP.net textboxes,
the calendar is not appearing. Below is my clientside code for textboxes.

<asp:TextBox id="FromDateDatepicker" onchange="disablePreviousDates()" runat="server" ></asp:TextBox>

<asp:TextBox id="ToDateDatepicker" runat="server"></asp:TextBox>

Please help…Thanks.

 

Hi sinjumujeeb,

Just before refreshing the datepicker element to get the new values, we need to destroy the widget, so try the following code, works flawlessly :

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
   function showCalendar() {
       $("#FromDateDatepicker").datepicker();
    }
    function disablePreviousDates()
    {
        $("#ToDateDatepicker").datepicker("destroy");
        if (document.getElementById('FromDateDatepicker').value != "") {
            var selectedFromDate = document.getElementById('FromDateDatepicker').value;
            var arrayForMonthsHaving31Days = [1, 3, 5, 7, 8, 10, 12];
            var arrayForMonthshaving30Days = [4, 6, 9, 11];

            var dateSelected = new Date(selectedFromDate);
            var month = dateSelected.getMonth();
            var year = dateSelected.getYear();
            var days;
            month++;
            for (var i = 0; i < 7; ++i) {
                if (month == arrayForMonthsHaving31Days[i]) days = 31;
                else if (month == arrayForMonthshaving30Days[i] && i < 4) days = 30;
            }
            if (days != 31 && days != 30 && (year % 100) % 4 != 0) days = 28;
            $("#ToDateDatepicker").datepicker({
                minDate: new Date(dateSelected),
                maxDate: new Date(year, month - 1, days)

            });
        }
        else
        {
            document.getElementById('FromDateDatepicker').value = "";
            document.getElementById('ToDateDatepicker').value = "";
            $("#FromDateDatepicker").datepicker();
            $("#ToDateDatepicker").datepicker();
        }
        
    }
</script>
</head>
    <form id="frm" runat="server">
<body onload="showCalendar()">
    From Date:<asp:TextBox ID="FromDateDatepicker" onchange="disablePreviousDates()" runat="server"></asp:TextBox><br />
    To Date:  <asp:TextBox ID="ToDateDatepicker" runat="server"></asp:TextBox>
   <%-- From Date : <input type="text" id="FromDateDatepicker" onchange="disablePreviousDates()" />
    To Date :   <input type="text" id="ToDateDatepicker" />--%>
</body>
        </form>
</html>

Hope this helps.

Thanks a lot Friend, Its working fine now.

Leave a Reply