Home » selenium-tutorial » CheckBox & Radio button

Newly Updated Posts

CheckBox & Radio button

CheckBox and Radio button both are handled in same way, it is generally can be handled by finding the locator and directly clicking on the element on Web Page but most of time it happens that the checkbox is by default checked and we need to verify and uncheck it or may be conditional check box need to be handled same in case of Radio button.

Lets discuss one by one in details.

CheckBox: To handle a check box, first we find its locator using any of the technique as discussed in previous topic (by id, name, xpath , css etc ) and directly click to the that element. But if the checkbox is already checked then in case we need to check by our test case whether it is checked or not.

For this we have a mehod which is isSelcted() , it return a boolean and according to it we can make condition either to check or uncheck. Let go to the coding part to get it more clear.

public Boolean Flag =false; //Define this globally after the class at class level

//Take all the element of checkbox in list 
List checkBoxes = driver.findElements(By.xpath("//input[@name='firstname']"));  

// This line will check whether the first check box is checked or unchecked and will return boolean      
  Boolean  Flag = checkBoxes.get(0).isSelected();

// If the Boolean is true, it will check the second check box and come out of loop
          while(Flag){  
            driver.findElements(By.xpath("//input[@name='firstname']")).get(1).click();
     Flag=false;

            }  

Above code in eclipse will look like this at below in image

So the similar way we can handle the radio button on the web page.