Java - Selenium - Check radio buttons and checkboxes

By xngo on February 24, 2019

/**
 * Selenium v2: Un/Check radio buttons and check boxes.
 * It is assumed that Firefox is installed on your computer.
 * @Author: Xuan Ngo
 */ 
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class CheckExample2
{
  public static void main(String[] args)
  {
    // All actions will be applied to Firefox.
    WebDriver oWebDriver = new FirefoxDriver();
 
    // Open the webpage.
    oWebDriver.get("https://openwritings.net/sites/default/files/selenium-test-pages/radio_checkbox.html");
 
    // Radio Button: Check Monday using XPATH locator.
    WebElement oRadioBtn = oWebDriver.findElement(By.xpath("//input[@value='Mon']"));
    oRadioBtn.click();
 
    // Checkbox: Uncheck Apple using CSS selector.
    WebElement oCheckBoxApple = oWebDriver.findElement(By.cssSelector("input[name='apple']")); // 2010-06-01: IE Driver doesn't support cssSelector yet.
    oCheckBoxApple.click();
 
    // Checkbox: Check Orange using CSS selector.
    WebElement oCheckBoxOrange = oWebDriver.findElement(By.cssSelector("input[name='orange']")); // 2010-06-01: IE Driver doesn't support cssSelector yet.
    oCheckBoxOrange.click();    
 
    pause(10000); // Pause so that you can see the results.
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.