Printing only the label of the enabled checkbox in the console with Selenium using Java

282 Views Asked by At

Is there a way to get the label of the selected checkbox without hardcoding it? I tried doing it with a loop and an if statement. The only checkbox that is selected/enabled is Option2. Within my for loop, when ran, it prints correctly the following in the console: These are the list of checkboxes : Option1 These are the list of checkboxes : Option2 These are the list of checkboxes : Option3

For my if statement that is within the for loop, I only want to print out the label of the enabled checkbox. It should display as the following: The selected webElement : Option2

When the code is ran, it prints out all the checkbox options as if they are all enabled.

I tried isEnabled() which returned true for all the items and I also tried isSelected() which returned false for all the items.

Please see my code below:

driver.get("https://www.rahulshettyacademy.com/AutomationPractice/");

driver.findElement(By.id("checkBoxOption2")).click();
System.out.println(driver.findElement(By.id("checkBoxOption2")).isEnabled());
List<WebElement> checkbox = driver.findElements(By.xpath("//div [@class='right-align']/fieldset/label"));
System.out.println(checkbox.size());


for (WebElement checkboxElement : checkbox) 
{
    String checkboxName =checkboxElement.getText();
    System.out.println("These are the list of checkboxes : " + checkboxName);
    
    if(checkboxElement.isEnabled()) {
        System.out.println("The selected webElement : " + checkboxName);
    }
}

enter image description here

1

There are 1 best solutions below

1
Richard On

.isEnabled() shows if the element is enabled in the web page.

You want to use checkboxElement.isSelected().