Home > Net >  Unable to select date in "https://demoqa.com/automation-practice-form" using C#
Unable to select date in "https://demoqa.com/automation-practice-form" using C#

Time:03-31

I am unable to select a date in practice form when I supplied the date it just appends in it although I have used the clear() command as well. I am new to C# and selenium.

Below is the code:

IWebElement calndr = driver.FindElement(By.Id("dateOfBirthInput"));
calndr.Clear();
calndr.SendKeys("08 April 2023");
calndr.SendKeys(Keys.Enter);

CodePudding user response:

You can not select date on that calendar by inserting the date as a sting there.
You have to open the calendar and then to select the year and the month with the use of Select Selenium object and select the date. You also should use Expected Conditions explicit waits there.
This should work:

using DotNetSeleniumExtras.WaitHelpers
using OpenQA.Selenium.Support.UI;

var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
var open_calendar = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("dateOfBirthInput")));
open_calendar.Click();
var selectYear = new SelectElement(driver.FindElement(By.ClassName("react-datepicker__year-select")));
selectYear.SelectByValue("2023"); 
Thread.Sleep(400);
var selectMonth = new SelectElement(driver.FindElement(By.ClassName("react-datepicker__month-select")));
selectYear.SelectByValue("3"); 
Thread.Sleep(400);
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Xpath("//div[contains(@class,'react-datepicker__day--008') and (not(contains(@class,'outside')))]"))).Click();

I know, it's not recommended to use hardcoded pauses but without them it will not work, this web page needs pauses between actions.

CodePudding user response:

This is what I used and works good for me.

//Initiate Driver instance and go to url
            IWebDriver driver = InitBrowser("chrome");
            driver.Url = "https://demoqa.com/automation-practice-form";

//Select DOB field then select date of month dropdown and assign to variable then select month by index
            driver.FindElement(By.Id("dateOfBirthInput")).Click();
            SelectElement MonthSelect = new SelectElement(driver.FindElement(By.ClassName("react-datepicker__month-select")));
            MonthSelect.SelectByIndex(3);

//Select year and assign to variable, then select year by index
            SelectElement YearSelect = new SelectElement(driver.FindElement(By.ClassName("react-datepicker__year-select")));
            YearSelect.SelectByIndex(123);

//Select the specific day you want by classname
            driver.FindElement(By.ClassName("react-datepicker__day--008")).Click();
  

All the class names were gotten from the html on the page. There should be no waits/thread.sleeps needed. Hope this works for you!

  • Related