Peter Penzov
Peter Penzov

Reputation: 1680

Add wait to checkbox select

I use this code with Java and Selenium to select a checkbox.

WebElement element = driver.findElement(By.id(inputId));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

Is it possible to add wait listener for the check button to be clickable? Sometimes the code fails with exception:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:

Upvotes: 0

Views: 1053

Answers (2)

Alexey R.
Alexey R.

Reputation: 8686

The more natural way would be:

Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(inputId)));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

until method will automatically return located element so that no need to have extra code.

Upvotes: 2

Prophet
Prophet

Reputation: 33361

You can simply add wait until the element is clickable.
Like this:

public void waitForElementToBeClickable(By element) {
    wait.until(ExpectedConditions.elementToBeClickable(element));
}

Then:

waitForElementToBeClickable(By.id(inputId));
WebElement element = driver.findElement(By.id(inputId));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

Upvotes: 2

Related Questions