six.strings.and.a.bit
six.strings.and.a.bit

Reputation: 527

How do I call a js function after I clicked on a particular date?

How do I call a Javascript function once I clicked on a particular date in the datepicker?

I guess onSelect and onClose functions may do the trick, but I can't seem to make things work.

Thanks in advance.

For example:

What I wanted to do is to display the age in a different textbox based on the date selected in the datepicker. I already made the JS function that does that, but I do not know how to call it after clicking a date in the datepicker.

This JS function calculates age based on the date given.

// Calculates age based on birth date
function calAge() {
var now = new Date();
var bday = form1.elements['bday'].value;

bD = bday.split('/');
if (bD.length == 3) {
    born = new Date(bD[2], bD[1] * 1 - 1, bD[0]);
    years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
    form1.elements['age'].value = (years - 100);
}

}

This is the datepicker. Am I right in calling the JS function?

$(".datepicker2")
    .datepicker({
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        dateFormat: "dd/mm/y",
        changeMonth: true,
        changeYear: true,
        onSelect: calAge
    })

Upvotes: 1

Views: 3558

Answers (2)

DaveR
DaveR

Reputation: 2483

When you initialise your datepicker you can define an onSelect function like this:

$('#datepicker').datepicker({ onSelect: function(date) {alert(date);}});

Here's a simple example:

http://jsfiddle.net/7jTNL/

Upvotes: 3

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

Bind the change event to the input.

$("#theInput")    .datepicker({params...})
                  .change(function(e){
                       //what you want to happen when a date is changed.
                  })

Upvotes: 0

Related Questions