Selecting Date on JQuery Datepicker

Hello Friends,

In this post we will see how to select specific date in JQuery Datepicker.

Its very easy to enter date as text by .sendKeys() method, but mostly when application uses JQuery Datepicker, it disables typing on the text-box. the text-box sets to read only.

While automating such screens we need to write logic which can interact with Datepicker and selects desired date.

Consider below example of Datepicker.
Html code for above example is
To automate this, we first break apart a problem.

  1. Decide which date we want to set 
  2. Read the current date from datepicker 
  3. Calculate difference between both dates in Months(difference will positive in case of set date is in future respective to current date & will negative when set date is in past respective to current date of datepicker) 
  4. Set loop depends on month difference and navigate the datepicker to specific month 
  5. Select the Day. 

Lets implement the above logic.
Note: we have used Joda Date Time Library for calculate date and time difference

SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat calDateFormat = new SimpleDateFormat("MMMM yyyy");
Date setDate=myDateFormat.parse("15/08/2014");
WebDriver driver = new FirefoxDriver();
// Switch to frame where the Menu Example is loaded
Date curDate = calDateFormat.parse(driver.findElement(By.className("ui-datepicker-title")).getText());
// Joda org.joda.time.Months class to calculate difference
// to do this converted Date to joda DatTime
int monthDiff = Months.monthsBetween(new DateTime(curDate).withDayOfMonth(1), new DateTime(setDate).withDayOfMonth(1)).getMonths();
boolean isFuture = true;
// decided whether set date is in past or future
isFuture = false;
// iterate through month difference
for(int i=1;i<=monthDiff;i++){
driver.findElement(By.className("ui-datepicker-" + (isFuture?"next":"prev"))).click();
// Click on Day of Month from table
driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']//a[text()='" + (new DateTime(setDate).getDayOfMonth()) + ";']")).click();

Hope this will help you…. you can directly use above code if your application is using JQuery Datepicker. Keep automating……


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s