A group of check boxes is created by giving two or more checkboxes the same control name. In the above example, the checkbox group control name is “color”. However, each checkbox in the group has a different associated value specified by the value attribute.
My favourite colors are:<br><br> <input type="checkbox" name="color" value="red"> Red<br> <input type="checkbox" name="color" value="yellow"> Yellow<br> <input type="checkbox" name="color" value="blue"> Blue<br> <input type="checkbox" name="color" value="orange"> Orange<br> <input type="checkbox" name="color" value="green"> Green<br> <input type="checkbox" name="color" value="purple"> Purple<br>
By observing above HTML code, we can see that, name of all the check boxes is same. So what we can do is, get the list of all check boxes by using attribute name and iterate over it. If found matching, then click on it.
Below piece of code illustrate the same. –
package learnAboutActionsClass; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class CheckBoxInSelenium { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.navigate().to("http://www.ironspider.ca/forms/checkradio.htm"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); List<WebElement> ListOfCheckBoxes = driver.findElements(By.name("color")); System.out.println("Number of check boxes pesent are: "+ListOfCheckBoxes.size()); for(int i=0; i< ListOfCheckBoxes.size() ; i++) { if(ListOfCheckBoxes.get(i).getAttribute("value").equalsIgnoreCase("Red")){ ListOfCheckBoxes.get(i).click(); } } } }
Refer below video for same explanation –