Friday, May 23, 2014

How to count the number of checkboxes checked in selenium webdriver ? or How to select multiple check box and verify ?

Note- Here 1st alternative checkbox has been selected, then it has been verified that which checkbox is selected and which is not selected.

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 MultipleCheckBox {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.gsmarena.com/samsung-phones-9.php");
        List<WebElement> checkBoxes = driver.findElements(By.xpath("//input[@type='Checkbox']"));
        for(int i=0; i<checkBoxes.size(); i=i+2){
            checkBoxes.get(i).click();
        }
        int checkedCount=0, uncheckedCount=0;
        for(int i=0; i<checkBoxes.size(); i++){
            System.out.println(i+" checkbox is selected "+checkBoxes.get(i).isSelected());
            if(checkBoxes.get(i).isSelected()){
                checkedCount++;
            }else{
                uncheckedCount++;
            }
        }
        System.out.println("number of selected checkbox: "+checkedCount);
        System.out.println("number of unselected checkbox: "+uncheckedCount);
    }
}



output-
0 checkbox is selected true
1 checkbox is selected false
2 checkbox is selected true
3 checkbox is selected false
4 checkbox is selected true
5 checkbox is selected false
6 checkbox is selected true
7 checkbox is selected false
8 checkbox is selected true
9 checkbox is selected false
number of selected checkbox: 5
number of unselected checkbox: 5

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Please find your ans here-
    http://selenium-makeiteasy.blogspot.in/search?q=annotation

    ReplyDelete
  3. Hello Mr.Sanjoy,
    I find your post is superb and very useful, but I am upset because there is no comment in your code that sometimes seem hard to understand.
    Orpy

    ReplyDelete