Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (19.7k points)

How can I check the checkboxes using id/xpath. Is there any method similar to select by visibletext for dropdown.

Going through the examples given for all other related questions I could not find a proper solution that works in a concise way that by few line or method I can check a checkbox or radio button.

Any help would be appreciated.

A sample HTML section is below:




        <span class="120927"> 

        <input id="ctl00_CM_ctl01_chkOptions_0" type="checkbox" name="ctl00$CM$ctl01$chkOptions$0"/> 

        <label for="ctl00_CM_ctl01_chkOptions_0">housingmoves</label> 






        <span class="120928"> 

        <input id="ctl00_CM_ctl01_chkOptions_1" type="checkbox" name="ctl00$CM$ctl01$chkOptions$1"/> 

        <label for="ctl00_CM_ctl01_chkOptions_1">Seaside & Country Homes</label> 





1 Answer

0 votes
by (62.9k points)
edited by

Use ID For Selection:

You can use the ID attribute to select a Radio Button or a CheckBox. We’ve provided the Webdriver command to click which you can apply to both types of elements.

Java code example to select checkbox/radio button.

 WebElement target = driver.findElement("checkbox1"));;

Call IsSelected() To Check The State:

 If you’ve selected/deselected a Checkbox/Radio Button and you want to check its final state. Then, you can use the <IsSelected> command to know the correct status of the element.

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;


public class findElementsTest {


   public static void main(String[] args) throws Exception {


      // Launch browser

      WebDriver driver = new FirefoxDriver();


      // Maximize window



      // Navigate to the URL



      // Sleep for 5 seconds



      // Store all the elements of the same category in the list of WebLements.

      List list = driver.findElements("radioButton"));


      // Create a boolean variable to store true/false.

      Boolean is_selected = list.get(0).isSelected();


      // If 'is_selected' is true that means the first radio button is

      // selected.

      if (is_selected == true) {


         // If the first radio button is selected by default then,

         // select the second radio button.



      } else {


         // If the first radio button is not selected then, click the first

         // radio button.





For further assistance, please go for online Selenium tutorials. 

Watch this Java video by Intellipaat:

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium course!

Browse Categories