Monday, October 4, 2010

Selenium-Select All Checkboxes

Few times back i just come across the situation where i require to select all the checkboxes on page. To do that one by one will make code to huge so i think about using loops for that. And here is the solution.

The following code will open the page that has 6 checkboxes and will check them all one by one.

import org.testng.annotations.*;
import com.thoughtworks.selenium.*;

public class TestCheckbox {

private Selenium selenium;

@BeforeClass
public void setUp(){

selenium = new DefaultSelenium("localhost", 2323, "*chrome", "http://qtp-help.blogspot.com");
selenium.start();
selenium.open("/");
}

@Test
public void selectAllCheckboxes() throws InterruptedException{
selenium.open("http://qtp-help.blogspot.com/2010/10/selenium-checkbox-example.html");

selenium.waitForPageToLoad("6000");
Thread.sleep(3000);
int totalCheckboxes = selenium.getXpathCount("//input[@type='checkbox']").intValue();
for (int i = 1; i < totalCheckboxes+1; i++) {

if(!selenium.isChecked("//input[@id='checkbox"+i+"']")){
selenium.click("//input[@id='checkbox"+i+"']");

}
}

}

}

selenium checkbox example

First Checbox

Second Checkbox


Third Checkbox


Fourth Checkbox


Fifth Checkbox


Sixth Checkbox




gaurang00hdhd