Link to home
Start Free TrialLog in
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

asked on

Change the color of spectfic dates in date picker control asp.net

Hi Experts,

I have a date picker control in my asp.net vb.net web project. I want to change the color of some specific dates. For example, when I check the "Weekend only" checkbox all the weekends for that month should have a different color. If a specific date has a Menu, then change the color and so on. I have attached a screen shot too.

This is my code to display the date picker.

 <script>
        $(document).ready(function () {
            $("input[id$='txtSelectedDate']").datepicker({
                showOn: "button",
                buttonImage: "images/Calender.png",
                buttonImageOnly: true,
            });
        });
    </script>

Thanks in advance.
DatePickerColor.png
Avatar of HainKurt
HainKurt
Flag of Canada image

there will be a css associated with datepicker

you should change them, or create your own and use it...

http://jqueryui.com/download/

when you download, you select the theme...
or there, you can design your own and download

http://jqueryui.com/themeroller/#!
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

ASKER

I am sorry, but did not understand anything.

Thanks.
Avatar of Dorababu M
On your check box changed event try this code

.ui-datepicker-week-end, .ui-datepicker-week-end a.ui-state-default {color:red;}
Hi,

Thanks for the reply. My checkbox is in the server side code. Can you please give me some detail code? How to send the checkbox value to the javascript and then if it is checked then make those dates red and if not checked then do not make them red.
Hi are you performing any server side operations with that checkbox
Hi Mr. Dorababu,

Can u please help me with the other part too? I have a  data set in the server side which contain a list of dates which are holidays. I have to change the back color of those dates in the datepicker.

Thanks in advance.
Hello for this you need to create a [WebMethod] and call this using Jquery. Try the following code

$(function () {
    DisableDates();
});

var HolidayList;
function getdates() {
    $.ajax({
        type: "POST",
        url: "/GetHolidayList/GetDates",
        data: '',
        success: function (data) {
            debugger;
            HolidayList= data;

            $("#pickdate").datepicker({
                dateFormat: 'dd-mm-yyyy',
                beforeShowDay: function (date) {
                    var dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
                    debugger;
                    if ($.inArray(dmy, HolidayList) == -1) {
                        return [true, ""];
                    } else {
                        return [false, "myclass", "Unavailable"];
                    }
                }
            });
        },
        dataType: "json",
        traditional: true
    });
}

Open in new window

Thank you very much for trying to help me. What do I need to write in the [WebMethod]? Also I have never used ajax before. Do I need to install anything to run ajax commands?

Thanks.
In [WebMethod] you need to write your own logic to get your dates. I don't think you need install any software as it is from JQUERY
Hi,

I have the dates in a dataset. So How can I pass that dataset using [Webmethod]? Can you show me some code please?

Thanks in advance.
Hi,

Thank you for sending the link. I will try it and get back to you.
Here is the code if you didn't get
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestingExamples.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"
        type="text/javascript"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/redmond/jquery-ui.css"
        rel="Stylesheet" type="text/css" />

    <script type="text/javascript">
        $(function () {
            var reserveddates = '[';
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/GetDates",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var xml = $.parseXML(response.d);
                    var dates = $(xml).find('Holiday_Date');
                    $.each(dates, function () {
                        reserveddates += '"' + $(this)[0].textContent.split('T')[0] + '",';
                    });
                    reserveddates += ']';
                    $("input[id$='txtSelectedDate']").datepicker({
                        beforeShowDay: function (date) {
                            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                            return [reserveddates.indexOf(string) == -1]
                        }
                    });
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="txtSelectedDate" runat="server"></asp:TextBox>
    </form>


</body>
</html>

Open in new window

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

namespace TestingExamples
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GetDates()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT Holiday_Date FROM Holiday_List"))
                {
                    cmd.Connection = con;
                    DataSet ds = new DataSet();
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(ds, "Customers");
                    }
                    return ds.GetXml();
                }
            }
        }

    }
}

Open in new window


User generated imageUser generated image
Hi,

Thank you very much for the code. But for some reason it is not working for me. From the dataset I am getting this data.  I changed the name of the form and the method name. Also I made the field name "MenuDate". But it does not make any difference.

 "<NewDataSet>    <Table>      <MenuDate>1900-01-01T00:00:00-06:00</MenuDate>    </Table>    <Table>      <MenuDate>2017-04-18T00:00:00-05:00</MenuDate>    </Table>    <Table>      <MenuDate>2017-04-27T00:00:00-05:00</MenuDate>    </Table>    <Table>

Thanks.
Can you check your browser console whether it is showing any errors? Is your page method is getting called from browser can you debug the JavaScript and let me know the response
Hi,

Thank you very much for trying to help me. I think the web method is not getting called.  I put a break point in the web method and also in the Java script. But did not get any error either.

Thanks.
Have you verified the console window in chrome browser? Which version of .Net you are working on
It is .net version 4. I just ran it with the debugger option on. Did not get any error. " verify the console window " mean what else do I need to do?

Thanks in advance.
Press F12 on chrome browser and navigate to console as per attached, see if there are any errors logged
User generated image
It is not showing any errors.

Thanks.
Hi Mr. Dorababu,

I just created a simple form and copied the code and it is working. But When I move the same code to my project, it is not working anymore. I created a simple form which uses the masterpage. Everything else is same. Please suggest!!

Thanks.
Ok are you using Master pages if so you need to call the control in JavaScript differently
ASKER CERTIFIED SOLUTION
Avatar of Dorababu M
Dorababu M
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Mr. Dorababu,

Thank you for your excellent help and patience. It worked!! Please help me with the last thing. Instead of disabling the dates I want to just change the color of the cell, but I need it to be clickable.

Thank you very much.
Try the following
Add this css in master page
    <style type="text/css">
        .Highlighted a {
            background-color: Red !important;
            background-image: none !important;
            color: White !important;
        }
    </style>

Open in new window

And the following in content page
 
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestingExamples.WebForm2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <asp:CheckBox ID="chkWeekend" runat="server" />
    <asp:TextBox ID="txtSelectedDate" runat="server"></asp:TextBox>
    <script type="text/javascript">
        var reserveddates;
        var weekenddate;
        function DisableSpecificDates(date) {
            var day = date.getDate(),
                    month = date.getMonth() + 1,
                year = date.getFullYear();
            if (month.toString().length < 2) month = '0' + month;
            if (day.toString().length < 2) day = '0' + day;
            var currentdate = [year, month, day].join('-');
            if (jQuery.inArray(currentdate, reserveddates) !== -1) {
                return [true, "Highlighted", ""];
            }
            else {
                return [true, "", ""];
            }
        }

        function DisableSpecificDatesWeekends(date) {
            var day = date.getDate(),
                    month = date.getMonth() + 1,
                year = date.getFullYear();
            if (month.toString().length < 2) month = '0' + month;
            if (day.toString().length < 2) day = '0' + day;
            var currentdate = [year, month, day].join('-');
            if (jQuery.inArray(currentdate, reserveddates) !== -1) {
                return [true, "Highlighted", ""];
            } else if (date.getDay() === 0 || date.getDay() === 6) {
                return [false, "disabled_week"]
            }
            else {
                return [true, "", ""];
            }
        }
        
        $(function () {

            reserveddates = []

            $.ajax({
                type: "POST",
                url: "WebForm2.aspx/GetDates",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var xml = $.parseXML(response.d);
                    var dates = $(xml).find('Holiday_Date');
                    $.each(dates, function () {
                        reserveddates.push($(this)[0].textContent.split('T')[0]);
                    });
                    $("input[id$='txtSelectedDate']").datepicker({
                        beforeShowDay: DisableSpecificDates
                        }
                    );
                }
            });

            $("input[id$='chkWeekend']").change(function () {
                $("input[id='txtSelectedDate']").datepicker("destroy");
                if ($("input[id$='chkWeekend']").is(':checked')) {
                    $("input[id$='txtSelectedDate']").datepicker('option', { beforeShowDay: DisableSpecificDatesWeekends })
                }
                else {
                    $("input[id$='txtSelectedDate']").datepicker('option', { beforeShowDay: DisableSpecificDates })
                }
            })
        });
    </script>
</asp:Content>

Open in new window

Thanks a lot for your wonderful help!!!
Is it working as expected?
Yes Sir, it is better than expected.  Thank you again for your wonderful support!