Tuesday, July 10, 2012

Restrict datepicker date using database driven dates

In this post we will be discussing restricting dates in jQuery UI datepicker dates using database driven dates.

We can restrict date using beforeShowDay event of the datepicker. Inside this function we can return [true] if we want the date to be enabled and return [false] if we want to disable date.

Let’s first get the date from server. For simplicity we will simply return an in memory date array like below-
    [WebMethod]
    public static List<string> GetDates()
    { 
        List<string> arr= new List<string>();
        arr.Add("2012-07-12");
        arr.Add("2012-07-25");
        arr.Add("2012-07-28");
        arr.Add("2012-07-13");
        arr.Add("2012-07-20");
        return arr;
    }
We can call this method from jQuery ajax like below-
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/redmond/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: "{}",
                url: "jquery datepicker fill with sql database dates.aspx/GetDates",
                dataType: "json",
                success: function (data) {
                    //enable date picker 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>
In the success method we can enable the datepicker and restrict the date by using the date from server (data.d). The code goes here-
$('#TextBox1').datepicker({
        minDate: new Date(2012, 6, 10),
        maxDate: new Date(2012, 8, 28),
        beforeShowDay: function (date) {
            function addZero(no) {
                if (no < 10) {
                    return "0" + no;
                } else {
                    return no;
                }
            }

        var date_str = [
        addZero(date.getFullYear()),
        addZero(date.getMonth() + 1),
        addZero(date.getDate())
        ].join('-');

        if ($.inArray(date_str, data.d) != -1) {
            return [true];
        } else {
            return [false];
        }
    }
});
What we are doing inside beforeShowDay is preparing the date string(date_str) in the format yyyy-mm-dd and then checking whether this date exists in the array data.d. If exists return [true] else return [false].