Problems sending text to text box with onkeypress event using C # selenium webdriver

I have a text box with an onkeypress event that renders the page when I enter a value in the text box. Here I use selenium webdriver to populate a text box. Before filling in the text box, I use textbox.clear (). In this way, the onkeypress event is fired and the page gets rendered. Thus, the text box control is removed from the webdriver instance.

After the onkeypress event, this element does not fall into the webdriver list. This is the source tag of a specific text field:

<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 here. Please suggest some ideas for filling in the values ​​in the text box.

I use the following code to populate my text box:

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

Thanks in advance.

+5
source share
3 answers

I used the following JavaScript code to solve this problem.

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 loading and works great.

However, in JavaScript 23.0 and later, this JavaScript does not work. Otherwise, for Chrome 31.0 and IE 9, JavaScript works fine.

+2
source

You are probably looking at an event onchangethat fires upon execution clear().

The solution is to clear and set the text in one action, and not in separate calls. You can do this using a class Actions, the C # extension method is shown below.

onchange , .

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();
 }
}
+5

JS injection is not a smart solution all the time, I suggest you go with @Faiz. In addition, writing code for a specific scenario or specific page will give you enormous pain during the maintenance phase.

0
source

All Articles