AndreasT
AndreasT

Reputation: 2337

Add custom parameter to jQuery UI Datepicker

I am looking for a way to add a parameter to the dates in the jQuery UI Datepicker. I am using the Datepicker to display course start dates. The parameter I need would be the id of the course that starts on that particular date.

I am initializing the datepicker like this:

$( "#datepicker" ).datepicker({
    dateFormat: 'dd-mm-yy',
    showWeek: true,
    firstDay: 1,
    numberOfMonths: 3,
    beforeShowDay: enableAllTheseDays
});

The function enableAllTheseDays looks like this:

function enableAllTheseDays(date) {
    var m = ('0'+parseInt(date.getMonth()+1)).slice(-2),
        d = ('0'+date.getDate()).slice(-2),
        i y = date.getFullYear();
    for (i = 0; i < enabledDays.length; i++) {
        if($.inArray((d + '-' + (m) + '-' + y).toString(),enabledDays) != -1) {
            return [true];
        }
    }
    return [false];
}

The enabledDays array contains all enabled dates, the rest of the calendar is disabled. In addition, I added an array with the course id to each date.

I figure I need to make the change in the enableAllTheseDays function, but I can not figure out how to get access to the underlying date object so that i can insert the course id as an attribute to the individual enabled dates. This way I could pass the course id as a parameter to the input field after date selection.

Thanks for any insight.

Upvotes: 2

Views: 4766

Answers (1)

sdeburca
sdeburca

Reputation: 845

Heres my attempt using the onSelect method for datepicker.

I have not updated the underlying Date object, instead just added a new data attribute to the "Result" input field. On select, it searches an object called courses (representing your list of course ids and dates) for a match for the selected date.

Inspect the input field with firebug/developer tools to see the data-course-id attribute update. First 3 days of the month have associated courses...

http://jsfiddle.net/Seandeburca/qbLwD/

var input = $("#datepicker");
var result = $("#result");

var courses = {
    "01-09-2013" : "javascript",
    "02-09-2013" : "history",
    "03-09-2013" : "biology",
    "10-09-2013": "physics"
};

input.datepicker({
   dateFormat: 'dd-mm-yy',
   showWeek: true,
   firstDay: 1,
   numberOfMonths: 3, 

   onSelect: function(dateText, pickerObj){

     result.attr("data-course-id", courses[dateText]); 
     course.innerHTML = courses[dateText]; 
   },

   altField: "#result"
});

Upvotes: 2

Related Questions