0

I'm new in javascript and I want to create a datepicker that highlight certain dates using a json response with a list of dates.

This is what I am trying:

var dates = [];
dates = getDays();
$(function () {
    $("#datepicker").datepicker({
        beforeShowDay: setHoliDays
    });
    function setHoliDays(date) {
        for (var i = 0; i < dates.lenght; i++) {
            if (dates[i] == date) {
                return [true, "green"];
            }
        }
        return [true, ""];
    }
});
function getDays() {
    var arr = [];
    $.getJSON("/getDates", function (data) {
        $.each(data, function (id, val) {
            arr.push(val);
        });
        return arr;
    });
} 

The JSON response is this:

["2013-03-18T12:00:00","2013-03-19T12:00:00","2013-03-20T12:00:00",
"2013-03-21T11:00:00","2013-03-21T10:00:00","2013-03-21T08:00:00",
"2013-03-25T10:00:00","2013-03-26T08:00:00","2013-03-27T09:00:00",
"2013-03-28T08:00:00","2013-03-28T09:00:00","2013-03-28T10:00:00",
"2013-03-28T11:00:00","2013-03-28T12:00:00"]

What am I doing wrong?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Rafael Carrillo
  • 2,772
  • 9
  • 43
  • 64
  • 4
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Mar 25 '13 at 19:07
  • 2
    How about simply loading all the dates before you start the datepicker? It looks like a simple request here, without any params sent... – raina77ow Mar 25 '13 at 19:08
  • hi @raina77ow I can load all dates, but the idea is when the user changes month load that month dates and highlight them.. – Rafael Carrillo Mar 25 '13 at 19:57

1 Answers1

0

Your getDays function is making an asynchronous call. That means that the method returns (nothing in this case) before the response is actually received from your remote resource. To make use of this response, your callback function will need to create the array and save it somewhere (global variable is easiest but certainly is not recommended for reasons I won't go into here). Then your setHoliDays function can make use of this.

Given that you are already making use of a global, your callback could end something like:

$.each(data,function(id,val){
  arr.push(val);
});
dates = arr;
Mike Clark
  • 11,769
  • 6
  • 39
  • 43