Home > Software engineering >  How to click on a year in calendar with Selenium using JavaScript
How to click on a year in calendar with Selenium using JavaScript

Time:01-25

I am trying to write a Selenium test with JavaScript but was unable to fill calendar data. It is using a dropdown menu:

const {Builder, By, Key} = require('selenium-webdriver')


const test2 = async () => {

let driver = await new Builder().forBrowser('chrome').build()
await driver.manage().window().maximize()
await driver.get('https://demoqa.com/automation-practice-form')
let calendar = 
driver.findElement(By.xpath("//input[@id='dateOfBirthInput']"))
await calendar.click()
let month = driver.findElement(By.xpath("//select[@class='react- 
datepicker__month-select']"))
await month.click()
await month.sendKeys(Key.DOWN, Key.DOWN, Key.RETURN)

let year = driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]")).value = "1988"

How can I clcik on value that I need? Console logging year gives me 1988, but I don't know how to select it in the browser. Is there any other way besides pressing Key.DOWN 35 times? I cannot use Select class in JavaScript.

CodePudding user response:

You can use the option tag to set values directly in the dropdown without opening it. Also, if your option is not found in the dropdown, an error will be thrown. You can handle it in a try block

month = "May"
year = "1988"
let driver = await new Builder().forBrowser('chrome').build()
await driver.manage().window().maximize()
await driver.get('https://demoqa.com/automation-practice-form')
let calendar = driver.findElement(By.xpath("//input[@id='dateOfBirthInput']"))
await calendar.click()
let month = driver.findElement(By.xpath("//select[@class='react-datepicker__month-select']/option[text()='" month "']"))
await month.click()

let year = driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]/option[text()='" year "']"))
await year.click()

CodePudding user response:

Don't have a JavaScript environment. However executing a javascript does the job.

Using Python clients:

element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#dateOfBirthInput")))
driver.execute_script("arguments[0].value = arguments[1]", element, "24 Jan 2023")

Browser Snapshot:

DOB


Execution in the Console

Command

document.getElementById('dateOfBirthInput').value='24 Jan 2023'

Snapshot:

console

  • Related