简体   繁体   中英

isSelected() method for checkbox always returns true

I want to turn on the toggle button if any toggle button is in disabled state, I wanted to let it be if the toggle button is already in enabled state.

List<WebElement> allToggle = driver.findElements(By.xpath("//body//******-******-****authoring//div//table//td//label"));

for (WebElement Toggle : allToggle) 
{
    if (!Toggle.isSelected()) 
    {
        Toggle.click();
    }
}

I don't know where I am being wrong.

Note:- Type of the button is Checkbox

You trying to invoke isSelected() for label element (based on xpath you've provided).

Based on official Selenium javadoc https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebElement.html#isSelected()

This operation only applies to input elements such as checkboxes, options in a select and radio buttons.

So isSelected() always returns true for non-input elements.

Solution proposed

Correct your xpath to refer corresponding input element, not label .

It can be some <input type="checkbox"> element in page source.

Also note that for some modern checkbox implementation those input elements can be hidden and even not directly clickable, anyway, highly likely you'll have to invoke isSelected() against those elements, but still need to click on label to toggle.

So you'll need to iterate by element index and get checkbox input and toggle label both.

List<WebElement> checkboxInputs = driver.findElements(By.xpath("some-xpath-part-you-need-to-determine/input"));

List<WebElement> allToggle = driver.findElements(By.xpath("//body//******-******-****authoring//div//table//td//label"));

int checkboxesCount = allToggle.size();

for (int i = 0; i < checkboxesCount; i++;) {
    if (!checkboxInputs.get(i).isSelected()) {
        allToggle.get(i).click();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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