Handle datePicker in selenium using JavaScript

In this article, will talk about how to Handle datePicker in selenium using JavaScript.
Suggested post to read:
In old applications, the datepicker was in old style, that is, it was a kind of dropdowns, by using select class. But in new applications now, Datepicker are not Select element.
Datepicker are in fact table with set of rows and columns. To select a date, you just have to navigate to the cell where our desired date is present. Look at the below snapshot.
So, to handle this datePicker, we will write a java script, in which firstly we will enable the datebox (which is restricted by default to enter the value manually rather than selecting it from calendar pop-up). Then We will clear that filed & then enter the date by using sendKeys() method.
Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandleDatePcikerUsingJavaScript {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.redbus.in/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //This will select From date 
  WebElement elementFromDate = driver.findElement(By.id("onward_cal"));
  ((JavascriptExecutor)driver).executeScript ("document.getElementById('onward_cal').removeAttribute('readonly',0);"); // Enables the from date box
  elementFromDate.clear();
  elementFromDate.sendKeys("18-Aug-2017"); //Enter date in required format
  
  
 }

}

Hope this helps !!

Leave Comment

Your email address will not be published. Required fields are marked *

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories