Naren
Naren

Reputation: 1350

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.

Upvotes: 5

Views: 3149

Answers (3)

Karthikeyan
Karthikeyan

Reputation: 2724

JS injection is not a wise solution all the time, i would suggest you to go with @Faiz.Also, writing a code for a scenario specific or page specific will give you tremendous pain in maintenance phase.

Upvotes: 0

Naren
Naren

Reputation: 1350

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.

Upvotes: 2

Faiz
Faiz

Reputation: 3256

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

Upvotes: 6

Related Questions