Choosing a date from a calendar using JavaScriptExecutor in Selenium

Having trouble selecting a calendar date using JavaScriptExecutor in Selenium. No errors are popping up in the console, and I can't figure out why. Can someone lend a hand? Check out the Selenium code snippet below.

package SeleniumSessions;

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.chrome.ChromeDriver;

public class SelectCalendarByJS {

    public static void main(String[] args) {


        System.setProperty("webdriver.chrome.driver","F:\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();

        driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.get("https://www.makemytrip.com/");

        WebElement date = driver.findElement(By.xpath("//input[@id = 'departure']"));

        String dateVal = "Friday, 19 Jun 2020";

        selectDateByJS(driver, date, dateVal);

    }

    public static void selectDateByJS(WebDriver driver , WebElement element , String dateVal) {
        JavascriptExecutor js = ((JavascriptExecutor)driver);
        js.executeScript("arguments[0].setAttribute('value','"+dateVal+"');", element);

    }
}

Here's the HTML DOM for the attribute being selected.

<input data-cy="departure" id="departure" type="text" class="fsw_inputField font20" readonly="" value="Friday, 19 Jun 2020">

Answer №1

The challenge with the date picker element on makemytrip is that it does not accept keyboard input. While your code might work for Expedia where you can modify the value attribute of the text field, Makemytrip requires a different approach. You need to click on the element and then select the date using a specific method, as demonstrated in the code snippet below. In Makemytrip's date selection process, the chosen date is displayed in a separate element (indicated by the P tag) rather than within the original element.

  @Test
    public void test() throws InterruptedException {
         driver.manage().window().maximize();
         driver.manage().deleteAllCookies();

         driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         WebElement date = driver.findElement(By.xpath("//*[@id=\"root\"]/div/div[2]/div/div/div[2]/div[1]/div[3]"));

         date.click();

        // System.out.println(driver.findElement(By.xpath()));

         Thread.sleep(3000);
         String dateVal = "Tue Jun 16 2020";
        selectDateByJS(driver, dateVal);

        Thread.sleep(3000);
    }

    public static void selectDateByJS(WebDriver driver, String dateVal) {

        JavascriptExecutor js = ((JavascriptExecutor)driver);
        js.executeScript("arguments[0].click();", driver.findElement(By.xpath("//div[@class='DayPicker-Day' and @aria-label='"+dateVal+ "']")));

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to highlight specific text in React components that is passed from an object?

This is the page HTML content where an object is created. A portion of the description needs to be emphasized: const agencyProps = { title: "Managed agency selection", paragraph: "Strengten your onboarding process", videoImage: { ...

Dealing with a socket.io CORS problem

After deciding to implement a websocket on my website, I opted to utilize the socket.io library. However, I've encountered a CORS error: Access to XMLHttpRequest at 'http://localhost:2021/socket.io/?EIO=4&transport=polling&t=NlbFGS2&apos ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Tips on resolving the issue of an Axios post request not appearing in a get request in React

When using axios to make a post request in this code, a new username is posted, but there is an issue with retrieving the posted name from the API. How can I fix this problem to view my posted request? const App = () => { const [data, setData] = u ...

Combining d3 and vue.js for enhanced interactive visualizations

I am currently in the process of integrating D3 with vue.js and I am following a straightforward guide available here: The guide suggests appending a new div for each new bar, which I have successfully accomplished using a custom directive as shown in the ...

Is it possible to fix the rightmost column in a scrollable HTML/CSS table with Angular when using overflow-x?

Is there a way to lock the right-most column in an HTML CSS Angular table that is scrollable using overflow-x? I have attempted using the sticky property and also creating two tables side by side, but neither method has successfully achieved the desired ...

Error with shader in webgl/three.js

i'm struggling with some issues in three js and need help with parallax mapping. vertex shader : varying vec3 v_pos; varying vec3 v_nrm; varying vec2 v_txc; void main(){ v_pos = position; v_nrm = normal; v_txc = uv; gl_Positi ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

Displaying the advancement of XHR accomplished through web workers

Is there a way to upload multiple files to the server using AJAX without web workers and still show progress to the user? I'm aware that web workers can't access UI elements, so looking for alternatives or workarounds. ...

Exploring the usage of promises with data in VueJS async components

Experimenting with VueJS 2.0 RC and utilizing the fetch API to retrieve data for certain components. Here's a sample scenario: const Component = { template: '#comp', name: "some-component", data: function () { return { basic ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

Problem with AngularJS function execution - require a delay in executing the second function

I am developing a small utility in AngularJS to manage the shopping cart for users. Here is the code snippet from my cart-service.js file: var myStoreCartService = angular.module("myStoreCartService", []); myStoreCartService.factory('Cart', fu ...

Incorporating click functionality in React for a to-do list feature

I've recently developed a task management application using React. However, I've encountered a couple of issues with the functionality. I am unable to mark tasks as completed by simply clicking on them, and the option to clear completed tasks by ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

Tips for keeping an image stationary when hovering over it

I'm in need of some assistance. Despite my best efforts, I have been unable to achieve the desired outcome. I am looking to create a scenario where an image remains in place even when the mouse hovers over it. Essentially, I want the image to stay vis ...

Display JSON content in a div depending on the selected option value

Seeking a more efficient way to load data from a JSON file based on the user-selected option. Currently, I am using multiple else if statements for each state, but it feels repetitive and cumbersome. Is there a better approach? Here's a snippet of my ...

The E2E test was successful in the local environment, but encountered issues when run in Jenkins using Protractor and Jasmine 2

We recently integrated e2e testing with our Jenkins system and initially had success running the tests both locally and from Jenkins as part of our build pipeline. After making changes to reflect updates at the end of the sprint and confirming that the te ...

Using a script to properly close HTML tags

It seems like a straightforward task, but I'm not sure where to start looking for the solution. What I'm trying to accomplish is this. I have a script that scans for the strings [gallery]. When it finds [gallery], it replaces the tag with an ima ...

What causes an error when jqXHR.abort() is invoked in the beforeSend function?

Attempting to interrupt ajax call with beforeSend in case of a specific condition. Upon executing jqXHR.abort() or return false, I encounter the following error message: TypeError: $.ajax(...).fail is not a function .fail(function (jqXHR, textStatus, er ...