ASP.net and Popup Calendar

Capodecina
Permabanned
Joined
31 Dec 2003
Posts
5,172
Location
Barrow-In-Furness
Have any of you created a popup calendar using the ASP.net built in Calendar control?

It can't be an AJAX one and I have no java experience so i'm at a loss. Every tutorial i've tried never seems to work.

Can anyone help?

Thanks :)

(You've probably seen loads of ASP threads from me, my first project will be finished when I do this so a big thanks to especially Stelly and also KevinCB, along with the rest of you who helped)
 
can you not just use the built in asp calendar control and then attach it to a popup window using javascript? You could have a small calendar icon and onclick will open the calendar in larger popup window. Sorry I don't have much experience of it but was just messing with calendar controls the other day for something.
 
Yes you can but like I said i'm useless with javascript.

I've tried a few tutorials to do this but they never seem to work, it's probably because the calendar control is within another control.
 
I had the same problem and had to use javascript.

Heres the code

Code:
<script>
    
        var t
    
        function SearchAsType()
        {
            if (t != '')
            {
                clearTimeout(t);
            }
            t = setTimeout('__doPostBack(\'ctl00_MainContent_txtSearch\',\'\')', 250);
        }
        
        function SearchAsType2()
        {
            if (t != '')
            {
                clearTimeout(t);
            }
            t = setTimeout('__doPostBack(\'ctl00_MainContent_txtSearchTo\',\'\')', 250);
        }
   
        function SetEnd (TB)
        {
            if (TB.createTextRange)
            {
                var FieldRange = TB.createTextRange();
                FieldRange.moveStart('character', TB.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }
        }
        
        function maskKeyPress2(objEvent) 
        {
             return true;
        }
        
        var datePickerDivID = "ctl00_MainContent_datepicker";
        var iFrameDivID = "ctl00_MainContent_datepickeriframe";

        var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
        var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
        var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
        var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
        var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
          
        // these variables define the date formatting we're expecting and outputting.
        // If you want to use a different format by default, change the defaultDateSeparator
        // and defaultDateFormat variables either here or on your HTML page.
        var defaultDateSeparator = "/";		// common values would be "/" or "."
        var defaultDateFormat = "dmy"	// valid values are "mdy", "dmy", and "ymd"
        var dateSeparator = defaultDateSeparator;
        var dateFormat = defaultDateFormat;

        /**
        This is the main function you'll call from the onClick event of a button.
        Normally, you'll have something like this on your HTML page:

        Start Date: <input name="StartDate"> 
        <input type=button value="select" onclick="displayDatePicker('StartDate');">

        That will cause the datepicker to be displayed beneath the StartDate field and
        any date that is chosen will update the value of that field. If you'd rather have the
        datepicker display beneath the button that was clicked, you can code the button
        like this:

        <input type=button value="select" onclick="displayDatePicker('StartDate', this);">

        So, pretty much, the first argument (dateFieldName) is a string representing the
        name of the field that will be modified if the user picks a date, and the second
        argument (displayBelowThisObject) is optional and represents an actual node
        on the HTML document that the datepicker should be displayed below.

        In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
        you to use a specific date format or date separator for a given call to this function.
        Normally, you'll just want to set these defaults globally with the defaultDateSeparator
        and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
        parameters here. An example of use is:

        <input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

        This would display the datepicker beneath the StartDate field (because the 
        displayBelowThisObject parameter was false), and update the StartDate field with
        the chosen value of the datepicker using a date format of dd.mm.yyyy
        */
        function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
        {
          var targetDateField = document.getElementsByName(dateFieldName).item(0);
          
          
          // if we weren't told what node to display the datepicker beneath, just display it
          // beneath the date field we're updating
          if (!displayBelowThisObject)
            displayBelowThisObject = targetDateField;
          
          // if a date separator character was given, update the dateSeparator variable
          if (dtSep)
            dateSeparator = dtSep;
          else
            dateSeparator = defaultDateSeparator;
          
          // if a date format was given, update the dateFormat variable
          if (dtFormat)
            dateFormat = dtFormat;
          else
            dateFormat = defaultDateFormat;        
          
          drawDatePicker(targetDateField, getElementPosition(displayBelowThisObject).left, getElementPosition(displayBelowThisObject).top);
        }


        /**
        Draw the datepicker object (which is just a table with calendar elements) at the
        specified x and y coordinates, using the targetDateField object as the input tag
        that will ultimately be populated with a date.

        This function will normally be called by the displayDatePicker function.
        */
        function drawDatePicker(targetDateField, x, y)
        {
          //alert(targetDateField.value);  
          var dt = getFieldDate(targetDateField.value);
          //alert(dt);
          // the datepicker table will be drawn inside of a <div> with an ID defined by the
          // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
          // document we're working with, add one.
          if (!document.getElementById(datePickerDivID)) {
            //alert('TEST');
            // don't use innerHTML to update the body, because it can cause global variables
            // that are currently pointing to objects on the page to have bad references
            //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
            var newNode = document.createElement("div");
            newNode.setAttribute("id", datePickerDivID);
            newNode.setAttribute("class", "dpDiv");
            newNode.setAttribute("style", "visibility: hidden;");
            document.body.appendChild(newNode);
          }
          
          // move the datepicker div to the proper x,y coordinate and toggle the visiblity
          var pickerDiv = document.getElementById(datePickerDivID);
         
          pickerDiv.style.position = "absolute";
           
          pickerDiv.style.left = x + "px";
          
          pickerDiv.style.top = y + "px";
          pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
          //alert(pickerDiv + 'hello');
          pickerDiv.style.zIndex = 10000;
          
          //alert(pickerDiv + 'hello');
          
          // draw the datepicker table
          refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
          
        }

        function getElementPosition(elemID)
        {
            var offsetTrail = document.getElementById(elemID);
            var offsetLeft = 0;
            var offsetTop = 0;
            while (offsetTrail)
            {
                offsetLeft += offsetTrail.offsetLeft;
                offsetTop += offsetTrail.offsetTop;
                offsetTrail = offsetTrail.offsetParent;
            }
           
            return {left:offsetLeft,top:offsetTop};
        }
        
        /**
        This is the function that actually draws the datepicker calendar.
        */
        function refreshDatePicker(dateFieldName, year, month, day)
        {
          // if no arguments are passed, use today's date; otherwise, month and year
          // are required (if a day is passed, it will be highlighted later)
          var thisDay = new Date();
          
          if ((month >= 0) && (year > 0)) {
            thisDay = new Date(year, month, 1);
          } else {
            day = thisDay.getDate();
            thisDay.setDate(1);
          }
          
          // the calendar will be drawn as a table
          // you can customize the table elements with a global CSS style sheet,
          // or by hardcoding style and formatting elements below
          var crlf = "\r\n";
          var TABLE = "<table cols=7 class='dpTable'>" + crlf;
          var xTABLE = "</table>" + crlf;
          var TR = "<tr class='dpTR'>";
          var TR_title = "<tr class='dpTitleTR'>";
          var TR_days = "<tr class='dpDayTR'>";
          var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
          var xTR = "</tr>" + crlf;
          var TD = "<td class='dpTD'";	// leave this tag open, because we'll be adding an onClick event
          var TD_title = "<td colspan=5 class='dpTitleTD'>";
          var TD_buttons = "<td class='dpButtonTD'>";
          var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
          var TD_days = "<td class='dpDayTD'>";
          var TD_selected = "<td class='dpDayHighlightTD'";	// leave this tag open, because we'll be adding an onClick event
          var xTD = "</td>" + crlf;
          var DIV_title = "<div class='dpTitleText'>";
          var DIV_selected = "<div class='dpDayHighlight'>";
          var xDIV = "</div>";
          
          // start generating the code for the calendar table
          var html = TABLE;
          
          // this is the title bar, which displays the month and the buttons to
          // go back to a previous month or forward to the next month
          html += TR_title;
          html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
          html += TD_title + DIV_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
          html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
          html += xTR;
          
          // this is the row that indicates which day of the week we're on
          html += TR_days;
          for(i = 0; i < dayArrayShort.length; i++)
            html += TD_days + dayArrayShort[i] + xTD;
          html += xTR;
          
          // now we'll start populating the table with days of the month
          html += TR;
          
          // first, the leading blanks
          for (i = 0; i < thisDay.getDay(); i++)
            html += TD + "&nbsp;" + xTD;
          
          // now, the days of the month
          do {
            dayNum = thisDay.getDate();
            TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
            
            if (dayNum == day)
              html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
            else
              html += TD + TD_onclick + dayNum + xTD;
            
            // if this is a Saturday, start a new row
            if (thisDay.getDay() == 6)
              html += xTR + TR;
            
            // increment the day
            thisDay.setDate(thisDay.getDate() + 1);
          } while (thisDay.getDate() > 1)
          
          // fill in any trailing blanks
          if (thisDay.getDay() > 0) {
            for (i = 6; i > thisDay.getDay(); i--)
              html += TD + "&nbsp;" + xTD;
          }
          html += xTR;
          
          // add a button to allow the user to easily return to today, or close the calendar
          var today = new Date();
          var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[today.getMonth()] + " " + today.getDate();
          html += TR_todaybutton + TD_todaybutton;
          html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>This Month</button> ";
          html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>Close</button>";
          html += xTD + xTR;
          
          // and finally, close the table
          html += xTABLE;
          
          document.getElementById(datePickerDivID).innerHTML = html;
          // add an "iFrame shim" to allow the datepicker to display above selection lists
          adjustiFrame();
        }


        /**
        Convenience function for writing the code for the buttons that bring us back or forward
        a month.
        */
        function getButtonCode(dateFieldName, dateVal, adjust, label)
        {
          var newMonth = (dateVal.getMonth() + adjust) % 12;
          var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
          if (newMonth < 0) {
            newMonth += 12;
            newYear += -1;
          }
          
          return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
        }


        /**
        Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
        variables at the beginning of this script library.
        */
        function getDateString(dateVal)
        {
          var dayString = "00" + dateVal.getDate();
          var monthString = "00" + (dateVal.getMonth()+1);
          dayString = dayString.substring(dayString.length - 2);
          monthString = monthString.substring(monthString.length - 2);
          
          switch (dateFormat) {
            case "dmy" :
              return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
            case "ymd" :
              return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
            case "mdy" :
            default :
              return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
          }
        }


        /**
        Convert a string to a JavaScript Date object.
        */
        function getFieldDate(dateString)
        {
          var dateVal;
          var dArray;
          var d, m, y;
          //alert(dateString)
          try {
            dArray = splitDateString(dateString);
            if (dArray) {
              switch (dateFormat) {
                case "dmy" :
                  d = parseInt(dArray[0], 10);
                  m = parseInt(dArray[1], 10) - 1;
                  y = parseInt(dArray[2], 10);
                  break;
                case "ymd" :
                  d = parseInt(dArray[2], 10);
                  m = parseInt(dArray[1], 10) - 1;
                  y = parseInt(dArray[0], 10);
                  break;
                case "mdy" :
                default :
                  d = parseInt(dArray[1], 10);
                  m = parseInt(dArray[0], 10) - 1;
                  y = parseInt(dArray[2], 10);
                  break;
              }
              dateVal = new Date(y, m, d);
            } else {
              dateVal = new Date(dateString);
            }
          } catch(e) {
            dateVal = new Date();
          }
          //alert(dateVal);
          return dateVal;
        }


        /**
        Try to split a date string into an array of elements, using common date separators.
        If the date is split, an array is returned; otherwise, we just return false.
        */
        function splitDateString(dateString)
        {
          var dArray;
          if (dateString.indexOf("/") >= 0)
            dArray = dateString.split("/");
          else if (dateString.indexOf(".") >= 0)
            dArray = dateString.split(".");
          else if (dateString.indexOf("-") >= 0)
            dArray = dateString.split("-");
          else if (dateString.indexOf("\\") >= 0)
            dArray = dateString.split("\\");
          else
            dArray = false;
          
          return dArray;
        }

        /**
        Update the field with the given dateFieldName with the dateString that has been passed,
        and hide the datepicker. If no dateString is passed, just close the datepicker without
        changing the field value.

        Also, if the page developer has defined a function called datePickerClosed anywhere on
        the page or in an imported library, we will attempt to run that function with the updated
        field as a parameter. This can be used for such things as date validation, setting default
        values for related fields, etc. For example, you might have a function like this to validate
        a start date field:

        function datePickerClosed(dateField)
        {
          var dateObj = getFieldDate(dateField.value);
          var today = new Date();
          today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
          
          if (dateField.name == "StartDate") {
            if (dateObj < today) {
              // if the date is before today, alert the user and display the datepicker again
              alert("Please enter a date that is today or later");
              dateField.value = "";
              document.getElementById(datePickerDivID).style.visibility = "visible";
              adjustiFrame();
            } else {
              // if the date is okay, set the EndDate field to 7 days after the StartDate
              dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
              var endDateField = document.getElementsByName("EndDate").item(0);
              endDateField.value = getDateString(dateObj);
            }
          }
        }

        */
        function updateDateField(dateFieldName, dateString)
        {
          var targetDateField = document.getElementsByName(dateFieldName).item(0);
          if (dateString)
            targetDateField.value = dateString;
            SearchAsType2();
          document.getElementById(datePickerDivID).style.visibility = "hidden";
          adjustiFrame();
          targetDateField.focus();
          
          // after the datepicker has closed, optionally run a user-defined function called
          // datePickerClosed, passing the field that was just updated as a parameter
          // (note that this will only run if the user actually selected a date from the datepicker)
          if ((dateString) && (typeof(datePickerClosed) == "function"))
            datePickerClosed(targetDateField);
        }
        
            /**
        Use an "iFrame shim" to deal with problems where the datepicker shows up behind
        selection list elements, if they're below the datepicker. The problem and solution are
        described at:

        http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
        http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
        */
        function adjustiFrame(pickerDiv, iFrameDiv)
        {
          if (!document.getElementById(iFrameDivID)) {
            // don't use innerHTML to update the body, because it can cause global variables
            // that are currently pointing to objects on the page to have bad references
            //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
            var newNode = document.createElement("iFrame");
            newNode.setAttribute("id", iFrameDivID);
            newNode.setAttribute("src", "javascript:false;");
            newNode.setAttribute("scrolling", "no");
            newNode.setAttribute("frameborder", "0");
            document.body.appendChild(newNode);
          }
          
          if (!pickerDiv)
            pickerDiv = document.getElementById(datePickerDivID);
          if (!iFrameDiv)
            iFrameDiv = document.getElementById(iFrameDivID);
          
          try {
            iFrameDiv.style.position = "absolute";
            iFrameDiv.style.width = pickerDiv.offsetWidth;
            iFrameDiv.style.height = pickerDiv.offsetHeight;
            iFrameDiv.style.top = pickerDiv.style.top;
            iFrameDiv.style.left = pickerDiv.style.left;
            iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
            iFrameDiv.style.visibility = pickerDiv.style.visibility;
          } catch(e) {
          }
    }
    
    </script>

Then Assign the javascript to a button in the page load C# method

Code:
searchcal.Attributes.Add("onclick", "displayDatePicker('ctl00_MainContent_txtSearch', 'ctl00_MainContent_txtSearch', 'dmy', '/');");

And this is the CSS to sort all the colors and styles

Code:
/*------Calender Style---------*/

 

.dpDiv {

          }

 

.dpTable {

          font-family: Tahoma, Arial, Helvetica, sans-serif;

          font-size: 12px;

          text-align: center;

          color: #FFFFFF;

          background-color: #99cccc;

          border: 1px solid #20a4b3;

          }

 

.dpTR {

          }

 

.dpTitleTR 

{

 

          }

 

.dpDayTR {

          }

 

.dpTodayButtonTR {

          }

 

.dpTD {

          cursor: pointer;

          }

 

.dpDayHighlightTD {

          background-color: #20A4B3;

          border: 1px solid #20a4b3;

          cursor: pointer;

          }

 

.dpTitleTD {

          cursor: pointer;

          }

 

.dpButtonTD {

          }

 

.dpTodayButtonTD {

          }

 

.dpDayTD {

          background-color: #20A4B3;

          border: 1px solid #20a4b3;

        font-weight: bold;

          color: #FFFFFF;

          }

 

.dpTitleText {

          font-size: 12px;

          color: #FFFFFF;

          font-weight: bold;

          }

 

.dpDayHighlight {

          color: #FFE303;

          font-weight: bold;

          }

 

.dpButton {

          font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;

          font-size: 10px;

          color: #FFFFFF;

          background: #20A4B3;

          font-weight: bold;

          padding: 0px;

          }

 

.dpTodayButton {

          font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;

          font-size: 10px;

          color: #FFFFFF;

          background: #20A4B3;

          font-weight: bold;

          }

Hope this helps :)
 
Sorry to be dim, I have no experience with using Java at all.

How do I assign the javascript code to a button? As in the actual code for doing it?

(All this would be so much easier if I could just use AJAX and the Toolkit ha-ha)
 
Yeah i am surpised they havent included something like this in ajax :p.

Ok to assign it to the button make a mathod in your c# file like this

Code:
protected void Page_Load(object sender, EventArgs e)
    {

}

Anything that goes in this method will be run each time the pages loads.

Then to assign the javascript to the button use this code inside the page load method.

Code:
#*ButtonName*#.Attributes.Add("onclick", "displayDatePicker('ctl00_MainContent_txtSearch', 'ctl00_MainContent_txtSearch', 'dmy', '/');");

As javascript cant see ASP items, the id's of the text field of where the date is to be inserted are different. So if you view the page in your browser and view the source code you will see that the name of the text box looks similar to this "ctl00_MainContent_txtSearch". Change the values in the assiging of the javascript to the text box where you want the date to appear (One value shows which control the calander will pop up over and the other is where the date is put - i cant renember which way round it is but you should be able to work that out with trial and error testing ;) ). It should then just work and look something like this

untitled-4.jpg
 
Thanks, sorry but where exactly should I put the javascript code? Just within the <head> tags of the page or within the page load event?
 
Last edited:
Ok no joy though, when I click the image button to try load the Calendar nothing happens. (I haven't added the css yet but I can't see why that would stop it working at all)

Here's the code behind:

Code:
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ImageButton1 As ImageButton
        ImageButton1 = CType(DetailsView1.FindControl("ImageButton1"), ImageButton)
        ImageButton1.Attributes.Add("onclick", "displayDatePicker('ctl00_MainContent_txtSearch', 'ctl00_MainContent_txtSearch', 'dmy', '/');")
    End Sub
 
And here's the page code...

Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
<script>
    
        var t
    
        function SearchAsType()
        {
            if (t != '')
            {
                clearTimeout(t);
            }
            t = setTimeout('__doPostBack(\'ctl00_MainContent_txtSearch\',\'\')', 250);
        }
        
        function SearchAsType2()
        {
            if (t != '')
            {
                clearTimeout(t);
            }
            t = setTimeout('__doPostBack(\'ctl00_MainContent_txtSearchTo\',\'\')', 250);
        }
   
        function SetEnd (TB)
        {
            if (TB.createTextRange)
            {
                var FieldRange = TB.createTextRange();
                FieldRange.moveStart('character', TB.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }
        }
        
        function maskKeyPress2(objEvent) 
        {
             return true;
        }
        
        var datePickerDivID = "ctl00_MainContent_datepicker";
        var iFrameDivID = "ctl00_MainContent_datepickeriframe";

        var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
        var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
        var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
        var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
        var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
          
        // these variables define the date formatting we're expecting and outputting.
        // If you want to use a different format by default, change the defaultDateSeparator
        // and defaultDateFormat variables either here or on your HTML page.
        var defaultDateSeparator = "/";		// common values would be "/" or "."
        var defaultDateFormat = "dmy"	// valid values are "mdy", "dmy", and "ymd"
        var dateSeparator = defaultDateSeparator;
        var dateFormat = defaultDateFormat;

        /**
        This is the main function you'll call from the onClick event of a button.
        Normally, you'll have something like this on your HTML page:

        Start Date: <input name="StartDate"> 
        <input type=button value="select" onclick="displayDatePicker('StartDate');">

        That will cause the datepicker to be displayed beneath the StartDate field and
        any date that is chosen will update the value of that field. If you'd rather have the
        datepicker display beneath the button that was clicked, you can code the button
        like this:

        <input type=button value="select" onclick="displayDatePicker('StartDate', this);">

        So, pretty much, the first argument (dateFieldName) is a string representing the
        name of the field that will be modified if the user picks a date, and the second
        argument (displayBelowThisObject) is optional and represents an actual node
        on the HTML document that the datepicker should be displayed below.

        In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
        you to use a specific date format or date separator for a given call to this function.
        Normally, you'll just want to set these defaults globally with the defaultDateSeparator
        and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
        parameters here. An example of use is:

        <input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

        This would display the datepicker beneath the StartDate field (because the 
        displayBelowThisObject parameter was false), and update the StartDate field with
        the chosen value of the datepicker using a date format of dd.mm.yyyy
        */
        function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
        {
          var targetDateField = document.getElementsByName(dateFieldName).item(0);
          
          
          // if we weren't told what node to display the datepicker beneath, just display it
          // beneath the date field we're updating
          if (!displayBelowThisObject)
            displayBelowThisObject = targetDateField;
          
          // if a date separator character was given, update the dateSeparator variable
          if (dtSep)
            dateSeparator = dtSep;
          else
            dateSeparator = defaultDateSeparator;
          
          // if a date format was given, update the dateFormat variable
          if (dtFormat)
            dateFormat = dtFormat;
          else
            dateFormat = defaultDateFormat;        
          
          drawDatePicker(targetDateField, getElementPosition(displayBelowThisObject).left, getElementPosition(displayBelowThisObject).top);
        }


        /**
        Draw the datepicker object (which is just a table with calendar elements) at the
        specified x and y coordinates, using the targetDateField object as the input tag
        that will ultimately be populated with a date.

        This function will normally be called by the displayDatePicker function.
        */
        function drawDatePicker(targetDateField, x, y)
        {
          //alert(targetDateField.value);  
          var dt = getFieldDate(targetDateField.value);
          //alert(dt);
          // the datepicker table will be drawn inside of a <div> with an ID defined by the
          // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
          // document we're working with, add one.
          if (!document.getElementById(datePickerDivID)) {
            //alert('TEST');
            // don't use innerHTML to update the body, because it can cause global variables
            // that are currently pointing to objects on the page to have bad references
            //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
            var newNode = document.createElement("div");
            newNode.setAttribute("id", datePickerDivID);
            newNode.setAttribute("class", "dpDiv");
            newNode.setAttribute("style", "visibility: hidden;");
            document.body.appendChild(newNode);
          }
          
          // move the datepicker div to the proper x,y coordinate and toggle the visiblity
          var pickerDiv = document.getElementById(datePickerDivID);
         
          pickerDiv.style.position = "absolute";
           
          pickerDiv.style.left = x + "px";
          
          pickerDiv.style.top = y + "px";
          pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
          //alert(pickerDiv + 'hello');
          pickerDiv.style.zIndex = 10000;
          
          //alert(pickerDiv + 'hello');
          
          // draw the datepicker table
          refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
          
        }

        function getElementPosition(elemID)
        {
            var offsetTrail = document.getElementById(elemID);
            var offsetLeft = 0;
            var offsetTop = 0;
            while (offsetTrail)
            {
                offsetLeft += offsetTrail.offsetLeft;
                offsetTop += offsetTrail.offsetTop;
                offsetTrail = offsetTrail.offsetParent;
            }
           
            return {left:offsetLeft,top:offsetTop};
        }
        
        /**
        This is the function that actually draws the datepicker calendar.
        */
        function refreshDatePicker(dateFieldName, year, month, day)
        {
          // if no arguments are passed, use today's date; otherwise, month and year
          // are required (if a day is passed, it will be highlighted later)
          var thisDay = new Date();
          
          if ((month >= 0) && (year > 0)) {
            thisDay = new Date(year, month, 1);
          } else {
            day = thisDay.getDate();
            thisDay.setDate(1);
          }
          
          // the calendar will be drawn as a table
          // you can customize the table elements with a global CSS style sheet,
          // or by hardcoding style and formatting elements below
          var crlf = "\r\n";
          var TABLE = "<table cols=7 class='dpTable'>" + crlf;
          var xTABLE = "</table>" + crlf;
          var TR = "<tr class='dpTR'>";
          var TR_title = "<tr class='dpTitleTR'>";
          var TR_days = "<tr class='dpDayTR'>";
          var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
          var xTR = "</tr>" + crlf;
          var TD = "<td class='dpTD'";	// leave this tag open, because we'll be adding an onClick event
          var TD_title = "<td colspan=5 class='dpTitleTD'>";
          var TD_buttons = "<td class='dpButtonTD'>";
          var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
          var TD_days = "<td class='dpDayTD'>";
          var TD_selected = "<td class='dpDayHighlightTD'";	// leave this tag open, because we'll be adding an onClick event
          var xTD = "</td>" + crlf;
          var DIV_title = "<div class='dpTitleText'>";
          var DIV_selected = "<div class='dpDayHighlight'>";
          var xDIV = "</div>";
          
          // start generating the code for the calendar table
          var html = TABLE;
          
          // this is the title bar, which displays the month and the buttons to
          // go back to a previous month or forward to the next month
          html += TR_title;
          html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
          html += TD_title + DIV_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
          html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
          html += xTR;
          
          // this is the row that indicates which day of the week we're on
          html += TR_days;
          for(i = 0; i < dayArrayShort.length; i++)
            html += TD_days + dayArrayShort[i] + xTD;
          html += xTR;
          
          // now we'll start populating the table with days of the month
          html += TR;
          
          // first, the leading blanks
          for (i = 0; i < thisDay.getDay(); i++)
            html += TD + "&nbsp;" + xTD;
          
          // now, the days of the month
          do {
            dayNum = thisDay.getDate();
            TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
            
            if (dayNum == day)
              html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
            else
              html += TD + TD_onclick + dayNum + xTD;
            
            // if this is a Saturday, start a new row
            if (thisDay.getDay() == 6)
              html += xTR + TR;
            
            // increment the day
            thisDay.setDate(thisDay.getDate() + 1);
          } while (thisDay.getDate() > 1)
          
          // fill in any trailing blanks
          if (thisDay.getDay() > 0) {
            for (i = 6; i > thisDay.getDay(); i--)
              html += TD + "&nbsp;" + xTD;
          }
          html += xTR;
          
          // add a button to allow the user to easily return to today, or close the calendar
          var today = new Date();
          var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[today.getMonth()] + " " + today.getDate();
          html += TR_todaybutton + TD_todaybutton;
          html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>This Month</button> ";
          html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>Close</button>";
          html += xTD + xTR;
          
          // and finally, close the table
          html += xTABLE;
          
          document.getElementById(datePickerDivID).innerHTML = html;
          // add an "iFrame shim" to allow the datepicker to display above selection lists
          adjustiFrame();
        }


        /**
        Convenience function for writing the code for the buttons that bring us back or forward
        a month.
        */
        function getButtonCode(dateFieldName, dateVal, adjust, label)
        {
          var newMonth = (dateVal.getMonth() + adjust) % 12;
          var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
          if (newMonth < 0) {
            newMonth += 12;
            newYear += -1;
          }
          
          return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
        }


        /**
        Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
        variables at the beginning of this script library.
        */
        function getDateString(dateVal)
        {
          var dayString = "00" + dateVal.getDate();
          var monthString = "00" + (dateVal.getMonth()+1);
          dayString = dayString.substring(dayString.length - 2);
          monthString = monthString.substring(monthString.length - 2);
          
          switch (dateFormat) {
            case "dmy" :
              return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
            case "ymd" :
              return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
            case "mdy" :
            default :
              return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
          }
        }


        /**
        Convert a string to a JavaScript Date object.
        */
        function getFieldDate(dateString)
        {
          var dateVal;
          var dArray;
          var d, m, y;
          //alert(dateString)
          try {
            dArray = splitDateString(dateString);
            if (dArray) {
              switch (dateFormat) {
                case "dmy" :
                  d = parseInt(dArray[0], 10);
                  m = parseInt(dArray[1], 10) - 1;
                  y = parseInt(dArray[2], 10);
                  break;
                case "ymd" :
                  d = parseInt(dArray[2], 10);
                  m = parseInt(dArray[1], 10) - 1;
                  y = parseInt(dArray[0], 10);
                  break;
                case "mdy" :
                default :
                  d = parseInt(dArray[1], 10);
                  m = parseInt(dArray[0], 10) - 1;
                  y = parseInt(dArray[2], 10);
                  break;
              }
              dateVal = new Date(y, m, d);
            } else {
              dateVal = new Date(dateString);
            }
          } catch(e) {
            dateVal = new Date();
          }
          //alert(dateVal);
          return dateVal;
        }


        /**
        Try to split a date string into an array of elements, using common date separators.
        If the date is split, an array is returned; otherwise, we just return false.
        */
        function splitDateString(dateString)
        {
          var dArray;
          if (dateString.indexOf("/") >= 0)
            dArray = dateString.split("/");
          else if (dateString.indexOf(".") >= 0)
            dArray = dateString.split(".");
          else if (dateString.indexOf("-") >= 0)
            dArray = dateString.split("-");
          else if (dateString.indexOf("\\") >= 0)
            dArray = dateString.split("\\");
          else
            dArray = false;
          
          return dArray;
        }

        /**
        Update the field with the given dateFieldName with the dateString that has been passed,
        and hide the datepicker. If no dateString is passed, just close the datepicker without
        changing the field value.

        Also, if the page developer has defined a function called datePickerClosed anywhere on
        the page or in an imported library, we will attempt to run that function with the updated
        field as a parameter. This can be used for such things as date validation, setting default
        values for related fields, etc. For example, you might have a function like this to validate
        a start date field:

        function datePickerClosed(dateField)
        {
          var dateObj = getFieldDate(dateField.value);
          var today = new Date();
          today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
          
          if (dateField.name == "StartDate") {
            if (dateObj < today) {
              // if the date is before today, alert the user and display the datepicker again
              alert("Please enter a date that is today or later");
              dateField.value = "";
              document.getElementById(datePickerDivID).style.visibility = "visible";
              adjustiFrame();
            } else {
              // if the date is okay, set the EndDate field to 7 days after the StartDate
              dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
              var endDateField = document.getElementsByName("EndDate").item(0);
              endDateField.value = getDateString(dateObj);
            }
          }
        }

        */
        function updateDateField(dateFieldName, dateString)
        {
          var targetDateField = document.getElementsByName(dateFieldName).item(0);
          if (dateString)
            targetDateField.value = dateString;
            SearchAsType2();
          document.getElementById(datePickerDivID).style.visibility = "hidden";
          adjustiFrame();
          targetDateField.focus();
          
          // after the datepicker has closed, optionally run a user-defined function called
          // datePickerClosed, passing the field that was just updated as a parameter
          // (note that this will only run if the user actually selected a date from the datepicker)
          if ((dateString) && (typeof(datePickerClosed) == "function"))
            datePickerClosed(targetDateField);
        }
        
            /**
        Use an "iFrame shim" to deal with problems where the datepicker shows up behind
        selection list elements, if they're below the datepicker. The problem and solution are
        described at:

        http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
        http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
        */
        function adjustiFrame(pickerDiv, iFrameDiv)
        {
          if (!document.getElementById(iFrameDivID)) {
            // don't use innerHTML to update the body, because it can cause global variables
            // that are currently pointing to objects on the page to have bad references
            //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
            var newNode = document.createElement("iFrame");
            newNode.setAttribute("id", iFrameDivID);
            newNode.setAttribute("src", "javascript:false;");
            newNode.setAttribute("scrolling", "no");
            newNode.setAttribute("frameborder", "0");
            document.body.appendChild(newNode);
          }
          
          if (!pickerDiv)
            pickerDiv = document.getElementById(datePickerDivID);
          if (!iFrameDiv)
            iFrameDiv = document.getElementById(iFrameDivID);
          
          try {
            iFrameDiv.style.position = "absolute";
            iFrameDiv.style.width = pickerDiv.offsetWidth;
            iFrameDiv.style.height = pickerDiv.offsetHeight;
            iFrameDiv.style.top = pickerDiv.style.top;
            iFrameDiv.style.left = pickerDiv.style.left;
            iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
            iFrameDiv.style.visibility = pickerDiv.style.visibility;
          } catch(e) {
          }
    }
    
    </script>
    <form id="form1" runat="server">
    <div>
        <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataKeyNames="TimeCode,Date" DataSourceID="ObjectDataSource1" DefaultMode="Insert">
            <Fields>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                    SortExpression="ID" />
                <asp:BoundField DataField="TimeCode" HeaderText="TimeCode" ReadOnly="True" SortExpression="TimeCode" />
                <asp:TemplateField HeaderText="Date" SortExpression="Date">
                    <EditItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:TextBox ID="DateTextBox" runat="server" Text='<%# Bind("Date") %>'></asp:TextBox>
                        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/calendar.png" />
                    </InsertItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Date") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Hours" HeaderText="Hours" SortExpression="Hours" />
                <asp:BoundField DataField="Username" HeaderText="Username" SortExpression="Username" />
                <asp:BoundField DataField="Comments" HeaderText="Comments" SortExpression="Comments" />
                <asp:CheckBoxField DataField="Approved" HeaderText="Approved" SortExpression="Approved" />
            </Fields>
        </asp:DetailsView>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete"
            InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetHours"
            TypeName="ManHoursTableAdapters.tblHoursTableAdapter" UpdateMethod="Update">
            <DeleteParameters>
                <asp:Parameter Name="Original_TimeCode" Type="Int32" />
                <asp:Parameter Name="Original_Date" Type="DateTime" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="TimeCode" Type="Int32" />
                <asp:Parameter Name="Date" Type="DateTime" />
                <asp:Parameter Name="Hours" Type="Int32" />
                <asp:Parameter Name="Username" Type="String" />
                <asp:Parameter Name="Comments" Type="String" />
                <asp:Parameter Name="Approved" Type="Boolean" />
                <asp:Parameter Name="Original_TimeCode" Type="Int32" />
                <asp:Parameter Name="Original_Date" Type="DateTime" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="TimeCode" Type="Int32" />
                <asp:Parameter Name="Date" Type="DateTime" />
                <asp:Parameter Name="Hours" Type="Int32" />
                <asp:Parameter Name="Username" Type="String" />
                <asp:Parameter Name="Comments" Type="String" />
                <asp:Parameter Name="Approved" Type="Boolean" />
            </InsertParameters>
        </asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>

Any ideas?

Thanks for the help so far :)
 
The problem is where you are adding the attribute in the VB script file. You are still using my "ctl00_MainContent_txtSearch". As you dont have an item on the page called this it doesnt know where to place the calendar. To get the right value to put in here do the following

View the page in internet explorer/firefox.

Then right click to view the scource code.

scroll down untill you find the imagebutton in the code and copy the name property of this element. (It should look something like "ct100_MainContent_Imagebutton1", it may be longer/have a differnet number or both but it should look similar to that)

Then copy this value in instead of my "ct100_maincontent_txtSearch". So your attribute assisgning line will look similar to this

Code:
ImageButton1.Attributes.Add("onclick", "displayDatePicker('ctl00_MainContent_ImangeButton1', 'ctl00_MainContent_ImageButton1', 'dmy', '/');")

No problem with the help, i was stuck on this for ages as i had to hack the calendar code to get it to work with asp :p. Took me like 2 days :p
 
Nearly there!

The calendar pops up but closes straight away?

Yeah I used the AJAX control toolkit one as a temporary solution while i've developer the rest of the site, i've come back to it now though because I can;t ust AJAX when the website is deployed.
 
Nearly there!

The calendar pops up but closes straight away?

Yeah I used the AJAX control toolkit one as a temporary solution while i've developer the rest of the site, i've come back to it now though because I can;t ust AJAX when the website is deployed.

Oppps forgot to mention that the button has to be in an update pannel :p. This should stop the calendar from closing :)
 
Ah just realised that you can't use ajax so update panels are out of the question :p.

The reason why the calendar is closing is beacise the button is casueing a postback so if you cange the button to an image it should be fine (However i have never tried it :p)
 
Ah just realised that you can't use ajax so update panels are out of the question :p.

The reason why the calendar is closing is beacise the button is casueing a postback so if you cange the button to an image it should be fine (However i have never tried it :p)

I might be able to get AJAX installed on the web server.... i'll enquire about it. It would be great if we could get the toolkit too but that's nut supported so it's unlikely.

AJAX is supported though and is part of 3.5, so I should be able to do that.

I'll get back to you soon, thanks a lot for the help :)
 
It pops up now but it's not bringing any value back?

I've got the imagebutton inside an update panel.

Thanks again
 
Ok thats good. The way to return the date selected is to change one of the parameters that the displayDatePicker method takes. I cant rememeber if it is the 1st or 2nd perameter but you sould be able to find that out. All you need is the name of the textbox (Find it the same way that you found the name of the image button ;) ). Then just change one of the arguments in the displayDatePicker method wherer you assign the javascript in the VB script. :) . Let me know if it works
 
Ah that's cracked it.

Thanks a lot, I tried at least 4 or 5 tutorials (although it was a while ago and they made use of the ASP.net Calendar rather than a custom one).

Have you got no problem with me using this code for a project?
 
Not at all as i got it from a free site. It was orginaly made to just work with normaly html pages, however i just modded it a bit so it would work in ASP. I would like to see the site once it has been done though if that would be possible :p . I like to see other peoples creations :)
 
I've noticed a problem. I'm using it in a detailsview that has the date picker and two other drop down lists.

If I select a value from both of the drop down lists first and then try use the popup calendar it loads and closes straight away.

It doesn't do it when I only select a value from one of the drop downs?
 
Back
Top Bottom