0

Html of input box with type number looks as below

<input id="noofItems" type="number" max="99" min="1" class="form-control" data-bind="value: noofItems" />

In my selenium test i have code which inputs number in that input box

[FindsBy(How = How.Id, Using = "noofItems"), CacheLookup]
private HtmlElement ItemsInput;

ItemsInput.WaitForVisible().SendKeys(Keys.Control + "a");
ItemsInput.WaitForVisible().SendKeys(Keys.Control + "x");
ItemsInput.WaitForVisible().SendKeys("2");
ItemsInput.WaitForVisible().SendKeys(Keys.Return); // need this to reload dom
ItemsInput.Click();

by default input box has value 1 but when test runs then i want to change to 2. But sometimes value changes to 12 instead of 2.

How to resolve this? I am using chromedriver.

DevelopmentIsMyPassion
  • 3,541
  • 4
  • 34
  • 60

2 Answers2

1

A bit more about WaitForVisible() method would have helped us to debug the issue in a better way. However as you are invoking SendKeys() to a <input> tag ideally you need to induce WebDriverWait for the ElementToBeClickable().

Again, instead of using Id you can use either of the following Locator Strategies:

  • CssSelector:

    [FindsBy(How = How.CssSelector, Using = "input.form-control#noofItems"), CacheLookup]
    private HtmlElement ItemsInput;
    
  • XPath:

    [FindsBy(How = How.XPath, Using = "//input[@class='form-control and @id='noofItems'']"), CacheLookup]
    private HtmlElement ItemsInput;
    

Finally, instead of using Keys.Control + "a" and Keys.Control + "x" you can use the much proven and robust Clear() method as follows:

ItemsInput.WaitForVisible().Click(); //preferably wait for ElementToBeClickable()
ItemsInput.Clear();
ItemsInput.SendKeys("2");
ItemsInput.SendKeys(Keys.Return);

PS: Once the element is returned after being clickable you can invoke Clear() and SendKeys() simultaneously without any further waiters.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    but isnt Id attribute more robust than anything else as it directly pinpoints element on page – DevelopmentIsMyPassion Nov 13 '19 at 09:46
  • I have also embedded the link of the detailed discussion wrt Id/Css/XPath in the answer itself within [`Locator Strategies`](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890) – undetected Selenium Nov 13 '19 at 09:51
  • None of solution worked which you provided :( Infact looks like this is working ItemsInput.SendKeys(Keys.Backspace); ItemsInput.Clear(); – DevelopmentIsMyPassion Nov 13 '19 at 10:01
0

It seems the default value returns if the field is empty. You can try to change it without deleting it

ItemsInput.WaitForVisible().SendKeys(Keys.Control + "a");
ItemsInput.WaitForVisible().SendKeys("2");

As a work around, you can also set the value attribute with JavaScript

driver.ExecuteScript("arguments[0].setAttribute('value', arguments[1]);", ItemsInput, 2);
Guy
  • 46,488
  • 10
  • 44
  • 88