Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having issues while sending text to a textbox which has onkeypress event using c# selenium webdriver

I am having a textbox which has onkeypress event which performs a page render when the value is entered to textbox. Here I am using selenium webdriver to fill the textbox. Before filling the textbox I am using textbox.clear(). So the onkeypress event get called and page gets rendered. So the textbox control is removed from webdriver instance.

After the onkeypress event taking place, the element is not getting listed in the webdriver. This is the source tag of the particular textbox:

<input id="ctl00_ctl00_ContentPlaceHolder1_cphMainContent_wzrDREvent_txtNftnTime" class="OpCenter_DateBox" type="text" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" onchange="javascript:setTimeout('__doPostBack(\'ctl00$ctl00$ContentPlaceHolder1$cphMainContent$wzrDREvent$txtNftnTime\',\'\')', 0)" name="ctl00$ctl00$ContentPlaceHolder1$cphMainContent$wzrDREvent$txtNftnTime">

And you can see the onkeypress event used here. Please suggest some ideas for filling the values in textbox.

I am using the following code to fill my text box:

element.Clear();
element.SendKeys(value);

Thanks in advance.

like image 269
Naren Avatar asked Apr 30 '13 10:04

Naren


2 Answers

You are probably looking at the onchange event being fired when you perform clear().

A solution is to clear and set text in one action, rather than in separate calls. You can do this by using the Actions class, the below C# extension method shows how.

The onchange event will fire once you lose focus from the text field element.

public static class WebElementExtensions
{
 public void ClearAndSetText(this IWebElement element, string text)
 {
    Actions navigator = new Actions(driver);
        navigator.Click(element)
            .SendKeys(Keys.End)
            .KeyDown(Keys.Shift)
            .SendKeys(Keys.Home)
            .KeyUp(Keys.Shift)
            .SendKeys(Keys.Backspace)
            .SendKeys(text)
            .Perform();
 }
}
like image 171
Faiz Avatar answered Jan 01 '23 11:01

Faiz


I have used the following JavaScript code to overcome this issue.

if (!(webDriver.GetType().FullName).Contains("IE"))
            {
                // To stop the page postback in Firefox and chrome
                ((IJavaScriptExecutor)webDriver).ExecuteScript("window.stop();");
            }

The above code stops the page load and it works perfectly.

However, in Firefox 23.0 and above, this JavaScript is not working. Otherwise, for Chrome 31.0 and IE 9, the JavaScript works fine.

like image 37
Naren Avatar answered Jan 01 '23 12:01

Naren