Dennis
Dennis

Reputation: 297

How to send numerical values to an input tag using Selenium C#

I know this might be a repeated question but I tried various methods to solve this one but couldn't solve the situation

enter image description here enter image description here

HTML code copied from the website

<input name="ctl00$TabContainer1$tpMain$ContentPlaceHolder1$Ins$txtDob" type="text" value="(dd/mm/yyyy)" maxlength="10" id="ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob" onselect="javascript:if(this.value=='(dd/mm/yyyy)') this.value='';this.style.color='';" onblur="javascript:InputValidation(this,'Date','Date of Birth','(dd/mm/yyyy)');" onclick="javascript:if(this.value=='(dd/mm/yyyy)') this.value='';this.style.color='';" onkeydown="return autodate(this)" onchange="javascript:CheckChanges();" onkeypress="return onlyNumbersWithForwardslash();" style="width:90%;" tabindex="0">

My code goes like this

string dob = startDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
string[] array = dob.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
char[] Chararray = string.Join(string.Empty, array).ToCharArray();

IWebElement DobElement = driver.FindElement(By.XPath("//*[@id='ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob']")); // .Id("ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob"));
    DobElement.Clear();

    foreach (char s in Chararray)
    {
         int num = Int32.Parse(s.ToString());
         DobElement.SendKeys(""+num);
    }

anyone help is appreciated to input numerical numbers to the textbox

Upvotes: 0

Views: 340

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193078

As the desired element is a JavaScript enabled element, so to send a chracter sequence within the <input> field you need to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:

  • CssSelector:

    IWebElement DobElement = driver.FindElement(By.CssSelector("input[id$='_Ins_txtDob'][name$='txtDob'][onblur*='InputValidation')]"));
    DobElement.Click();
    DobElement.Clear();
    DobElement.SendKeys(""+num);
    
  • XPath:

    IWebElement DobElement = driver.FindElement(By.XPath("//input[contains(@id, '_Ins_txtDob') and contains(@name, 'txtDob')][contains(@onblur, 'InputValidation')]"));
    DobElement.Click();
    DobElement.Clear();
    DobElement.SendKeys(""+num);
    

Upvotes: 2

Related Questions