Monday, November 4, 2013

All about accessing check boxes using web driver

In all my previous examples we checked how we can extract, Locate and input data for various web input types. In this example lets see about the "Check Boxes". How we can locate, Print  the values, get the count ect.. Below code has different aspects of how we can access check boxes. 

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Test3 {
public static void main(String[] args) throws Exception {
//Locate the element and gets the check boxes count 
WebDriver A = new FirefoxDriver();
A.get("http://www.echoecho.com/htmlforms09.htm");
List<WebElement> B = A.findElements(By.xpath("//table[3]/tbody/tr/td/table/tbody/tr/td/input"));
int count = B.size();
System.out.println(count);
//Prints the values inside the check box
for (int i = 0; i <count; i++) {
System.out.println(B.get(i).getAttribute("Value"));
   }
//Clicking on each check box in a loop 
for (int j = 0; j < count; j++) {
B.get(j).click();
System.out.println("Clicked On"+ B.get(j).getAttribute("Value"));
     }

//Checks if the values are clicked already 
for (int k = 0; k < count; k++) {
if (B.get(k).getAttribute("checked") != null)
System.out.println(B.get(k).getAttribute("value")+"--- Is Cecked");
else 
System.out.println(B.get(k).getAttribute("value")+"---Is not checked"); 
  }


//Reset the check boxes unchecked status if they are already clicked
for (int u = 0; u < count; u++) {
if (B.get(u).getAttribute("checked") != null)
B.get(u).click();} 
System.out.println("After Reseting");

//Check initially if values are checked or not in a loop 
for (int k = 0; k < count; k++) {
if (B.get(k).getAttribute("checked") != null)
System.out.println(B.get(k).getAttribute("value")+"--- Is Cecked");
else 
System.out.println(B.get(k).getAttribute("value")+"---Is not checked");                                                                                     }


}

}

The output of this program is 

3

Milk
Butter
Cheese

Clicked OnMilk
Clicked OnButter
Clicked OnCheese

Milk--- Is Cecked
Butter---Is not checked
Cheese--- Is Cecked

After Reseting
Milk---Is not checked
Butter---Is not checked
Cheese---Is not checked

2 comments:

  1. Very well done!!! Please keep up your work coming. Appreciate your efforts to document for readers.

    ReplyDelete
    Replies
    1. Thanks :) Happy that these are useful to yall :)

      Delete