简体   繁体   English

如何清除文本框中的文本?

[英]How to clear the text within the text box?

webdriver clear() is not clearing the existing text webdriver clear()不清除现有文本

I have tried clear() and it's not working, so tried .sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE)) but my senior doesn't want me to use the keys. 我已经尝试过clear() ,但是它不起作用,所以尝试了.sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE))但是我的前辈不希望我使用这些键。 So unsure how can i clear the text? 所以不确定如何清除文本?

HTML of the element: 元素的HTML:

<input name="Quantity_110787" type="number" min="0" ng-model="invoiceLine.quantity" class="form-control ng-pristine ng-valid ng-not-empty ng-valid-min ng-touched" ng-keypress="$ctrl.preventKey($event)" aria-invalid="false">

Code trials: 代码试用:

public void sendText(String text) {
        for (String control : controls) { 
        if(getWebDriver().findElement(By.cssSelector(control)).getAttribute("type").contains("number")) {
                getWebDriver().findElement(By.cssSelector(control)).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE), text);
                break;
            }
        }

I want the text field to be cleared, so i can enter the new text. 我希望清除文本字段,因此可以输入新文本。 Please help. 请帮忙。

This should work as @Dark Knight said, 这应该像@Dark Knight所说的那样工作,

driver.findElement("locator").clear();

try to click before 尝试点击之前

 driver.findElement("locator").click();
 driver.findElement("locator").clear();

else try using sendKeys 否则尝试使用sendKeys

driver.findElement("locator").click();
driver.findElement("locator").sendKeys("");

else try JS: 否则尝试JS:

WebElement wb = driver.findElement("locator");
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value='';", wb);

Thanks, 谢谢,

尝试这样做。

driver.findElement("locator").clear();

The desired element is a Angular element so to invoke clear() method you need to induce WebDriverwait for the element to be clickable and you can use either of the following solutions: 所需的元素是Angular元素,因此要调用clear()方法,需要诱导WebDriverwait使该元素可单击,并且可以使用以下任一解决方案:

  • cssSelector : cssSelector

     WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control.ng-pristine.ng-valid.ng-not-empty.ng-valid-min.ng-touched[type='number'][name^='Quantity_']"))); elem.click(); elem.clear(); 
  • xpath : xpath

     WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='form-control ng-pristine ng-valid ng-not-empty ng-valid-min ng-touched' and @type='number'][starts-with(@name, 'Quantity_')]"))); elem.click(); elem.clear(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM