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+"']");

}
}

}

}

3 comments:

Unknown said...

selenium.getXpathCount shows undefined. Please help.

THanks!

Unknown said...

May be XPath you are using is not correct.
Please use the XPather add-on of firefox to check if you are using the correct Xpath which will give you all the checkbox or not ???

joerooney said...

Hello sir your blog is really helpful
I have a question
Is is possible to have automation testing using java selenium to a page which has images and i need to check the images are appearing or not if yes can you give some sample code

Post a Comment