Popular Searches
Popular Course Categories
Popular Courses

Radio Buttons

HTML & Web Elements

Radio Buttons in Selenium

Radio buttons are common form elements used in web applications when users need to select one option from a group of mutually exclusive choices. In Selenium WebDriver, radio buttons can be located and interacted with using methods such as click(), isSelected(), isDisplayed(), and isEnabled().

Radio button automation is an important Selenium skill because registration forms, surveys, payment pages, booking systems, account settings, and configuration screens frequently use radio buttons to collect one choice from multiple options.

Selenium training commonly covers WebElements, forms, browser interactions, locators, and automation frameworks. Learn more about Selenium Training and Register for a Course Demo.


1. What is a Radio Button?

A radio button is an HTML form control that allows the user to select one option from a group of related options. Radio buttons are normally grouped using the same name attribute.

<input type="radio" name="gender" value="male"> Male

<input type="radio" name="gender" value="female"> Female

<input type="radio" name="gender" value="other"> Other

In this example, the three radio buttons belong to the same group because they use the same name="gender".


2. Why Radio Buttons are Important in Automation Testing

Radio buttons are frequently used when an application requires exactly one choice from a predefined set of options.

  • Selecting gender
  • Selecting payment methods
  • Choosing delivery methods
  • Selecting account types
  • Choosing subscription plans
  • Selecting shipping options
  • Choosing employment status
  • Selecting Yes or No options
  • Choosing preferred language
  • Selecting booking preferences


3. Basic HTML Structure of a Radio Button

<input type="radio" id="male" name="gender" value="male">

<label for="male">Male</label>

Important attributes include:

AttributePurpose
typeDefines the input as a radio button.
idProvides a unique identifier.
nameGroups related radio buttons.
valueRepresents the value submitted by the form.
classProvides CSS-based identification or styling.
checkedIndicates the default selected option.
disabledPrevents interaction with the radio button.


4. Radio Button Group

A radio button group normally contains multiple radio buttons with the same name attribute.

<input type="radio" name="payment" value="card"> Credit Card

<input type="radio" name="payment" value="upi"> UPI

<input type="radio" name="payment" value="cash"> Cash

When these controls are correctly grouped, selecting one option causes the previously selected option in that group to become unselected.


5. Radio Button vs Checkbox

Radio ButtonCheckbox
Normally used to select one option from a group.Can normally be used to select multiple independent options.
Options are usually mutually exclusive.Options can usually be selected independently.
Commonly grouped using the same name.Each checkbox can represent an independent choice.
Example: Male/Female/Other.Example: Java/Selenium/SQL.


6. Setting Up Selenium for Radio Button Testing

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class RadioButtonTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com");

        driver.quit();

    }

}


7. Locating a Radio Button Using ID

If the radio button has a unique and stable ID, the ID locator can be used.

WebElement maleRadio = driver.findElement(By.id("male"));

maleRadio.click();


8. Locating a Radio Button Using Name

WebElement radio = driver.findElement(By.name("gender"));

radio.click();

When several radio buttons share the same name, findElement() returns the first matching element. Therefore, use a more specific locator when you need a particular option.


9. Locating a Radio Button Using Class Name

WebElement radio = driver.findElement(

    By.className("gender-radio")

);

 

radio.click();

Class Name should be used carefully if multiple elements share the same class.


10. Locating a Radio Button Using Tag Name

WebElement radio = driver.findElement(By.tagName("input"));

radio.click();

This is usually too broad because a page may contain text fields, checkboxes, buttons, and other input elements.


11. Locating a Radio Button Using CSS Selector

WebElement radio = driver.findElement(

    By.cssSelector("input[type='radio']")

);

 

radio.click();


12. CSS Selector Using ID

WebElement radio = driver.findElement(

    By.cssSelector("#male")

);

 

radio.click();


13. CSS Selector Using Name and Value

WebElement radio = driver.findElement(

    By.cssSelector("input[name='gender'][value='male']")

);

 

radio.click();

This is useful when several radio buttons belong to the same group.


14. CSS Selector Using Multiple Attributes

WebElement radio = driver.findElement(

    By.cssSelector(

        "input[type='radio'][name='payment'][value='upi']"

    )

);

 

radio.click();


15. Locating Radio Button Using XPath

WebElement radio = driver.findElement(

    By.xpath("//input[@type='radio']")

);

 

radio.click();


16. XPath Using ID

WebElement radio = driver.findElement(

    By.xpath("//input[@id='male']")

);

 

radio.click();


17. XPath Using Name

WebElement radio = driver.findElement(

    By.xpath("//input[@name='gender']")

);

 

radio.click();


18. XPath Using Value

WebElement radio = driver.findElement(

    By.xpath("//input[@value='male']")

);

 

radio.click();


19. XPath Using Multiple Attributes

WebElement radio = driver.findElement(

    By.xpath("//input[@type='radio' and @value='male']")

);

 

radio.click();


20. XPath Using Label Text

Sometimes the radio input has limited identifying information while the associated label contains meaningful text.

WebElement radio = driver.findElement(

    By.xpath("//label[normalize-space()='Male']/preceding-sibling::input")

);

 

radio.click();


21. Using the click() Method

The click() method is used to select a radio button.

WebElement radio = driver.findElement(By.id("male"));

radio.click();

Clicking a different radio button in the same group normally changes the selection to the newly clicked option.


22. Understanding isSelected()

The isSelected() method checks whether a radio button is currently selected.

WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isSelected()) {

    System.out.println("Male option is selected");

} else {

    System.out.println("Male option is not selected");

}


23. Checking Radio Button Visibility

WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isDisplayed()) {

    System.out.println("Radio button is visible");

}


24. Checking Radio Button Enabled State

WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isEnabled()) {

    System.out.println("Radio button is enabled");

} else {

    System.out.println("Radio button is disabled");

}


25. Complete Radio Button State Validation

WebElement radio = driver.findElement(By.id("male"));

 

System.out.println("Displayed: " + radio.isDisplayed());

System.out.println("Enabled: " + radio.isEnabled());

System.out.println("Selected: " + radio.isSelected());


26. Select Radio Button Only If It Is Not Selected

Checking the current state before clicking makes the automation more predictable.

WebElement radio = driver.findElement(By.id("male"));

 

if (!radio.isSelected()) {

    radio.click();

}


27. Verify Radio Button Is Selected

WebElement radio = driver.findElement(By.id("male"));

 

radio.click();

 

if (radio.isSelected()) {

    System.out.println("Radio button selected successfully");

}


28. Verify Radio Button Is Not Selected

WebElement radio = driver.findElement(By.id("female"));

 

if (!radio.isSelected()) {

    System.out.println("Female option is not selected");

}


29. Selecting One Option From a Radio Group

WebElement upi = driver.findElement(

    By.cssSelector("input[name='payment'][value='upi']")

);

 

if (!upi.isSelected()) {

    upi.click();

}


30. Multiple Radio Buttons

A page can contain several radio buttons belonging to different groups.

<input type="radio" name="gender" value="male"> Male

<input type="radio" name="gender" value="female"> Female

 

<input type="radio" name="payment" value="card"> Card

<input type="radio" name="payment" value="upi"> UPI

There are two separate groups here: gender and payment.


31. Finding Multiple Radio Buttons

List<WebElement> radios = driver.findElements(

    By.cssSelector("input[type='radio']")

);


32. Counting Radio Buttons

List<WebElement> radios = driver.findElements(

    By.cssSelector("input[type='radio']")

);

 

System.out.println("Total radio buttons: " + radios.size());


33. Import Required for List

import java.util.List;


34. Selecting a Specific Radio Button by Value

WebElement radio = driver.findElement(

    By.cssSelector("input[type='radio'][value='female']")

);

 

radio.click();


35. Selecting a Specific Radio Button by Label

WebElement radio = driver.findElement(

    By.xpath("//label[normalize-space()='Female']/preceding-sibling::input")

);

 

radio.click();


36. Selecting Radio Button Based on User Choice

String expectedOption = "UPI";

 

WebElement radio = driver.findElement(

    By.xpath("//label[normalize-space()='" + expectedOption + "']/preceding-sibling::input")

);

 

if (!radio.isSelected()) {

    radio.click();

}


37. Selecting Radio Button Using a Dynamic XPath

String option = "Credit Card";

 

WebElement radio = driver.findElement(

    By.xpath("//input[@type='radio' and @value='" + option + "']")

);

 

radio.click();


38. XPath contains() for Dynamic Radio Button

WebElement radio = driver.findElement(

    By.xpath("//input[contains(@id,'payment_')]")

);

 

radio.click();


39. XPath starts-with() for Dynamic Radio Button

WebElement radio = driver.findElement(

    By.xpath("//input[starts-with(@id,'payment_')]")

);

 

radio.click();


40. Handling a Pre-Selected Radio Button

A radio button may already be selected when the page loads.

WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isSelected()) {

    System.out.println("Male is selected by default");

} else {

    radio.click();

}


41. Handling Disabled Radio Button

A disabled radio button cannot normally be selected through standard user interaction.

WebElement radio = driver.findElement(By.id("premium"));

 

if (radio.isEnabled()) {

    radio.click();

} else {

    System.out.println("Radio button is disabled");

}


42. Handling Radio Button With Label

<input type="radio" id="card" name="payment" value="card">

<label for="card">Credit Card</label>

The label is associated with the radio button through the for attribute.


43. Clicking the Label Instead of Radio Button

When the native radio button is hidden or visually replaced, the visible label may be the correct element to interact with.

WebElement label = driver.findElement(

    By.cssSelector("label[for='card']")

);

 

label.click();


44. Custom Styled Radio Button

Modern applications often hide the native radio input and use CSS to display a custom visual control.

<input type="radio" id="online" name="delivery" hidden>

<label for="online" class="custom-radio">

    Online Delivery

</label>

In such cases, Selenium may need to interact with the visible label or custom control.


45. Hidden Radio Button

WebElement radio = driver.findElement(By.id("online"));

 

System.out.println("Displayed: " + radio.isDisplayed());

If the native radio input is hidden, directly clicking it may result in an interaction exception. Identify the visible control associated with it.


46. ElementClickInterceptedException

ElementClickInterceptedException can occur when another element, overlay, popup, or UI component prevents the radio button from receiving the click.

try {

    WebElement radio = driver.findElement(By.id("male"));

    radio.click();

} catch (ElementClickInterceptedException e) {

    System.out.println("Radio button click was intercepted");

}


47. ElementNotInteractableException

This exception can occur when Selenium locates the radio button but it cannot currently be interacted with.

try {

    WebElement radio = driver.findElement(By.id("male"));

    radio.click();

} catch (ElementNotInteractableException e) {

    System.out.println("Radio button is not interactable");

}


48. NoSuchElementException

If Selenium cannot locate the required radio button, NoSuchElementException may occur.

try {

    WebElement radio = driver.findElement(By.id("male"));

    radio.click();

} catch (NoSuchElementException e) {

    System.out.println("Radio button was not found");

}


49. StaleElementReferenceException

A radio button reference can become stale if the page dynamically refreshes or the DOM element is replaced.

try {

    WebElement radio = driver.findElement(By.id("male"));

    radio.click();

} catch (StaleElementReferenceException e) {

    System.out.println("Radio button reference became stale");

}


50. Waiting for Radio Button Visibility

Dynamic applications may display radio buttons after page loading or after another user action.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement radio = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("male")

    )

);


51. Waiting for Radio Button to Become Clickable

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement radio = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("male")

    )

);

 

radio.click();


52. Implicit Wait for Radio Button

driver.manage().timeouts().implicitlyWait(

    Duration.ofSeconds(10)

);

 

WebElement radio = driver.findElement(By.id("male"));

radio.click();


53. Explicit Wait vs Implicit Wait

Implicit WaitExplicit Wait
Applies to element searches globally.Targets a specific condition.
Configured once.Configured where required.
Useful for general synchronization.Useful for dynamic UI conditions.
Less specific.More condition-specific.


54. Selecting Radio Button With JavaScript

JavaScript can sometimes be used as a fallback when normal Selenium interaction is blocked by a custom UI implementation.

JavascriptExecutor js = (JavascriptExecutor) driver;

 

WebElement radio = driver.findElement(By.id("male"));

 

js.executeScript("arguments[0].click();", radio);


55. Checking Radio Button State With JavaScript

JavascriptExecutor js = (JavascriptExecutor) driver;

 

Boolean selected = (Boolean) js.executeScript(

    "return arguments[0].checked;",

    radio

);

 

System.out.println("Selected: " + selected);


56. When Not to Use JavaScript Click

  • Do not use JavaScript click as the first solution.
  • Verify the locator first.
  • Check whether the radio button is visible.
  • Check whether the radio button is enabled.
  • Check whether an overlay is blocking it.
  • Use explicit waits when synchronization is the actual problem.
  • Use JavaScript only when the application's UI structure requires it.


57. Radio Buttons in a Registration Form

<form>

    <input type="radio" name="gender" value="male"> Male

    <input type="radio" name="gender" value="female"> Female

    <input type="radio" name="gender" value="other"> Other

    <button type="submit">Register</button>

</form>


58. Automating Gender Selection

WebElement female = driver.findElement(

    By.cssSelector("input[name='gender'][value='female']")

);

 

if (!female.isSelected()) {

    female.click();

}


59. Verifying Gender Selection

WebElement female = driver.findElement(

    By.cssSelector("input[name='gender'][value='female']")

);

 

female.click();

 

if (female.isSelected()) {

    System.out.println("Female option selected");

}


60. Testing Mutually Exclusive Behavior

One important radio button test is verifying that selecting one option unselects the previously selected option within the same group.

WebElement male = driver.findElement(

    By.cssSelector("input[name='gender'][value='male']")

);

 

WebElement female = driver.findElement(

    By.cssSelector("input[name='gender'][value='female']")

);

 

male.click();

System.out.println("Male: " + male.isSelected());

 

female.click();

 

System.out.println("Male: " + male.isSelected());

System.out.println("Female: " + female.isSelected());


61. Radio Button Group Validation

List<WebElement> genderOptions = driver.findElements(

    By.cssSelector("input[name='gender']")

);

 

int selectedCount = 0;

 

for (WebElement option : genderOptions) {

    if (option.isSelected()) {

        selectedCount++;

    }

}

 

System.out.println("Selected options: " + selectedCount);

For a properly grouped radio-button control where one selection is required, the expected selected count is normally one.


62. Verify Only One Radio Button Is Selected

Assert.assertEquals(

    selectedCount,

    1,

    "Exactly one radio button should be selected"

);


63. Verify No Radio Button Is Selected

Some optional radio groups may initially have no selection.

Assert.assertEquals(

    selectedCount,

    0,

    "No radio button should be selected initially"

);


64. Verify Default Radio Button

WebElement defaultOption = driver.findElement(

    By.cssSelector("input[name='delivery'][value='standard']")

);

 

Assert.assertTrue(

    defaultOption.isSelected(),

    "Standard delivery should be selected by default"

);


65. Selecting Payment Method

WebElement card = driver.findElement(

    By.cssSelector("input[name='payment'][value='card']")

);

 

if (!card.isSelected()) {

    card.click();

}


66. Selecting Delivery Method

WebElement express = driver.findElement(

    By.cssSelector("input[name='delivery'][value='express']")

);

 

express.click();


67. Selecting Subscription Plan

WebElement premium = driver.findElement(

    By.cssSelector("input[name='plan'][value='premium']")

);

 

premium.click();


68. Selecting Yes/No Radio Buttons

WebElement yes = driver.findElement(

    By.cssSelector("input[name='answer'][value='yes']")

);

 

yes.click();


69. Handling Radio Buttons by Label Text

String option = "Premium";

 

WebElement radio = driver.findElement(

    By.xpath("//label[normalize-space()='" + option + "']/preceding-sibling::input")

);

 

if (!radio.isSelected()) {

    radio.click();

}


70. Radio Button Inside a Table

Radio buttons may be used inside tables when the user must choose one item from a list.

<table>

    <tr>

        <td>

            <input type="radio" name="product" value="101">

        </td>

        <td>Laptop</td>

    </tr>

    <tr>

        <td>

            <input type="radio" name="product" value="102">

        </td>

        <td>Tablet</td>

    </tr>

</table>


71. Select Radio Button for a Specific Table Row

WebElement radio = driver.findElement(

    By.xpath("//tr[td[normalize-space()='Laptop']]//input[@type='radio']")

);

 

radio.click();


72. Radio Button in a Product Listing

WebElement product = driver.findElement(

    By.xpath("//div[contains(@class,'product')][.//span[normalize-space()='Laptop']]//input[@type='radio']")

);

 

product.click();


73. Radio Button Inside a Modal

WebElement modal = driver.findElement(By.id("settingsModal"));

 

WebElement radio = modal.findElement(

    By.cssSelector("input[type='radio']")

);

 

radio.click();


74. Radio Button Inside an Iframe

If the radio button is located inside an iframe, Selenium must switch to the iframe before locating it.

WebElement frame = driver.findElement(

    By.id("paymentFrame")

);

 

driver.switchTo().frame(frame);

 

WebElement radio = driver.findElement(

    By.id("card")

);

 

radio.click();

 

driver.switchTo().defaultContent();


75. Radio Button Inside Nested Iframes

driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

driver.findElement(By.id("card")).click();

 

driver.switchTo().defaultContent();


76. Radio Button in Shadow DOM

Modern web components may place radio buttons inside a Shadow DOM.

WebElement host = driver.findElement(

    By.cssSelector("custom-radio-group")

);

 

SearchContext shadowRoot = host.getShadowRoot();

 

WebElement radio = shadowRoot.findElement(

    By.cssSelector("input[type='radio']")

);

 

radio.click();


77. Radio Button in a Dynamic List

WebElement option = driver.findElement(

    By.xpath("//li[normalize-space()='Premium']")

);

 

WebElement radio = option.findElement(

    By.cssSelector("input[type='radio']")

);

 

radio.click();


78. Dynamic Radio Button IDs

Some applications generate IDs dynamically.

<input type="radio" id="option_827361" name="plan" value="premium">

A stable attribute such as name, value, or a stable surrounding container can be preferable to relying on the complete dynamic ID.


79. Handling Radio Button With Dynamic Value

String value = "premium";

 

WebElement radio = driver.findElement(

    By.xpath("//input[@type='radio' and @value='" + value + "']")

);

 

radio.click();


80. Radio Button Automation Flow

Start

  |

  v

Open Web Page

  |

  v

Locate Radio Button

  |

  v

Is Element Present?

  |

  +---- No ----> Handle Locator/Error

  |

 Yes

  |

  v

Is Radio Button Enabled?

  |

  +---- No ----> Verify Disabled State

  |

 Yes

  |

  v

Check Current Selection

  |

  +---- Selected ----> Continue

  |

  +---- Not Selected ----> Click

  |

  v

Verify Selected State

  |

  v

Verify Group Behavior

  |

  v

Continue Test

  |

  v

End


81. Common Radio Button Test Scenarios

ScenarioExpected Result
Radio button is visibleRadio button should be displayed.
Radio button is enabledUser should be able to select it.
Radio button is disabledUser should not be able to select it.
Radio button is selectedisSelected() should return true.
Radio button is not selectedisSelected() should return false.
Another option is selectedPrevious selection should change according to the radio group behavior.
Default option existsExpected option should be selected on page load.
Required group is emptyAppropriate validation should appear.
Radio button is dynamically loadedAutomation should wait for the element.
Radio button is inside iframeAutomation should switch into the iframe.


82. Radio Button Validation Checklist

  • Verify radio button visibility.
  • Verify radio button enabled state.
  • Verify default selection.
  • Verify selection behavior.
  • Verify mutually exclusive behavior.
  • Verify required-field validation.
  • Verify dynamic radio button behavior.
  • Verify custom styled radio buttons.
  • Verify radio buttons inside tables.
  • Verify radio buttons inside iframes.
  • Verify radio button behavior across supported browsers.


83. Common Mistakes While Automating Radio Buttons

  • Using a broad locator that matches multiple radio buttons.
  • Ignoring the name grouping.
  • Using unstable dynamic IDs.
  • Clicking without checking the current state when state-sensitive logic is required.
  • Ignoring disabled state.
  • Ignoring visibility.
  • Ignoring synchronization issues.
  • Using JavaScript unnecessarily.
  • Forgetting to switch into an iframe.
  • Not verifying the final selection.


84. Bad Radio Button Locator

driver.findElement(By.xpath("//input")).click();

This locator is too broad and may select an unrelated input field.


85. Better Radio Button Locator

WebElement radio = driver.findElement(

    By.cssSelector("input[type='radio'][name='gender'][value='male']")

);

 

radio.click();


86. Best Practices for Radio Button Automation

  • Use stable and unique locators.
  • Prefer ID when it is stable and unique.
  • Use CSS selectors or XPath when required.
  • Use the name attribute to understand radio groups.
  • Use value to distinguish options in the same group.
  • Use isSelected() to validate state.
  • Use isEnabled() before interaction when appropriate.
  • Use explicit waits for dynamic applications.
  • Verify the expected final selection.
  • Avoid unnecessary JavaScript execution.
  • Keep locators maintainable.
  • Use Page Object Model in larger automation frameworks.


87. Real-World Example: Registration Form

WebElement male = driver.findElement(

    By.cssSelector("input[name='gender'][value='male']")

);

 

WebElement female = driver.findElement(

    By.cssSelector("input[name='gender'][value='female']")

);

 

female.click();

 

Assert.assertTrue(

    female.isSelected(),

    "Female option should be selected"

);

 

Assert.assertFalse(

    male.isSelected(),

    "Male option should not be selected"

);


88. Real-World Example: Payment Method

String paymentMethod = "upi";

 

WebElement payment = driver.findElement(

    By.cssSelector(

        "input[type='radio'][name='payment'][value='" + paymentMethod + "']"

    )

);

 

if (!payment.isSelected()) {

    payment.click();

}

 

Assert.assertTrue(

    payment.isSelected(),

    "UPI payment option should be selected"

);


89. Real-World Example: Delivery Options

String delivery = "express";

 

WebElement option = driver.findElement(

    By.cssSelector(

        "input[type='radio'][name='delivery'][value='" + delivery + "']"

    )

);

 

option.click();

 

System.out.println(

    "Express delivery selected: " + option.isSelected()

);


90. Real-World Example: Subscription Plan

WebElement premium = driver.findElement(

    By.xpath("//input[@type='radio' and @value='premium']")

);

 

if (!premium.isSelected()) {

    premium.click();

}

 

Assert.assertTrue(

    premium.isSelected(),

    "Premium plan should be selected"

);


91. TestNG Radio Button Validation

import static org.testng.Assert.assertTrue;

 

WebElement radio = driver.findElement(

    By.id("male")

);

 

radio.click();

 

assertTrue(

    radio.isSelected(),

    "Radio button should be selected"

);


92. Complete TestNG Radio Button Test

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class RadioButtonTest {

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com");

    }

 

    @Test

    public void verifyGenderRadioButton() {

        WebElement female = driver.findElement(

            By.cssSelector(

                "input[name='gender'][value='female']"

            )

        );

 

        if (!female.isSelected()) {

            female.click();

        }

 

        Assert.assertTrue(

            female.isSelected(),

            "Female radio button should be selected"

        );

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}


93. Radio Button With Page Object Model

In a Page Object Model framework, radio button locators and interactions can be maintained inside the corresponding page class.

public class RegistrationPage {

 

    private WebDriver driver;

 

    private By maleRadio =

        By.cssSelector("input[name='gender'][value='male']");

 

    private By femaleRadio =

        By.cssSelector("input[name='gender'][value='female']");

 

    public RegistrationPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void selectMale() {

        WebElement radio = driver.findElement(maleRadio);

 

        if (!radio.isSelected()) {

            radio.click();

        }

    }

 

    public void selectFemale() {

        WebElement radio = driver.findElement(femaleRadio);

 

        if (!radio.isSelected()) {

            radio.click();

        }

    }

 

    public boolean isFemaleSelected() {

        return driver.findElement(femaleRadio).isSelected();

    }

}


94. Reusable Radio Button Utility Method

public void selectRadioButton(By locator) {

    WebElement radio = driver.findElement(locator);

 

    if (!radio.isSelected()) {

        radio.click();

    }

}


95. Reusable Radio Button Validation Method

public boolean isRadioButtonSelected(By locator) {

    return driver.findElement(locator).isSelected();

}


96. Radio Button Utility With Explicit Wait

public void selectRadioButton(By locator) {

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement radio = wait.until(

        ExpectedConditions.elementToBeClickable(locator)

    );

 

    if (!radio.isSelected()) {

        radio.click();

    }

}


97. Selecting Radio Button From Multiple Options

List<WebElement> options = driver.findElements(

    By.cssSelector("input[name='payment']")

);

 

for (WebElement option : options) {

    String value = option.getAttribute("value");

 

    if ("upi".equalsIgnoreCase(value)) {

        option.click();

        break;

    }

}


98. Finding Selected Radio Button From a Group

WebElement selectedOption = driver.findElement(

    By.cssSelector("input[name='payment']:checked")

);

 

System.out.println(

    "Selected payment: " +

    selectedOption.getAttribute("value")

);


99. CSS :checked Selector

The CSS :checked pseudo-class can be useful for locating the currently selected radio button.

WebElement selected = driver.findElement(

    By.cssSelector("input[name='gender']:checked")

);

 

System.out.println(

    selected.getAttribute("value")

);


100. Checking Whether a Radio Group Has a Selection

List<WebElement> selectedOptions = driver.findElements(

    By.cssSelector("input[name='gender']:checked")

);

 

if (selectedOptions.size() == 1) {

    System.out.println("One option is selected");

} else {

    System.out.println("No option is selected");

}


101. Counting Selected Radio Buttons

List<WebElement> selected = driver.findElements(

    By.cssSelector("input[type='radio']:checked")

);

 

System.out.println(

    "Selected radio buttons: " + selected.size()

);


102. Verifying a Specific Value Is Selected

WebElement selected = driver.findElement(

    By.cssSelector("input[name='payment']:checked")

);

 

String actualValue = selected.getAttribute("value");

 

Assert.assertEquals(

    actualValue,

    "upi",

    "UPI should be selected"

);


103. Required Radio Group Validation

Some forms require the user to select one option before submitting the form.

<input type="radio" name="delivery" value="standard" required>

<label>Standard</label>

 

<input type="radio" name="delivery" value="express" required>

<label>Express</label>

Automation should verify that the application provides appropriate validation when the required group has no selection.


104. Radio Button Test Case Format

Test Case IDTest ScenarioExpected Result
RAD001Verify radio button visibilityRadio button should be visible.
RAD002Verify radio button enabled stateRadio button should be enabled.
RAD003Select radio buttonSelected option should become active.
RAD004Select another optionPrevious option should be deselected within the same group.
RAD005Verify default selectionExpected option should be selected initially.
RAD006Verify required validationValidation should appear when no option is selected.
RAD007Verify disabled optionDisabled option should not be selectable.
RAD008Verify dynamic radio buttonAutomation should wait and interact correctly.


105. Radio Button Test Data Example

FieldPossible ValuesExpected Selection
GenderMale, Female, OtherFemale
PaymentCard, UPI, CashUPI
DeliveryStandard, ExpressExpress
PlanBasic, PremiumPremium
Account TypePersonal, BusinessBusiness


106. Radio Button Automation With Logging

WebElement radio = driver.findElement(By.id("premium"));

 

System.out.println(

    "Before selection: " + radio.isSelected()

);

 

if (!radio.isSelected()) {

    radio.click();

}

 

System.out.println(

    "After selection: " + radio.isSelected()

);


107. Radio Button Automation With Assertions

WebElement radio = driver.findElement(By.id("premium"));

 

if (!radio.isSelected()) {

    radio.click();

}

 

Assert.assertTrue(

    radio.isSelected(),

    "Premium radio button should be selected"

);


108. Testing Radio Button Group Behavior

WebElement card = driver.findElement(

    By.cssSelector("input[name='payment'][value='card']")

);

 

WebElement upi = driver.findElement(

    By.cssSelector("input[name='payment'][value='upi']")

);

 

card.click();

 

Assert.assertTrue(card.isSelected());

 

upi.click();

 

Assert.assertTrue(upi.isSelected());

Assert.assertFalse(card.isSelected());


109. Radio Button Group With Three Options

<input type="radio" name="plan" value="basic"> Basic

<input type="radio" name="plan" value="standard"> Standard

<input type="radio" name="plan" value="premium"> Premium

Only one option from this group should normally be selected at a time because all three inputs share the same name.


110. Selecting Premium From a Three-Option Group

WebElement premium = driver.findElement(

    By.cssSelector(

        "input[name='plan'][value='premium']"

    )

);

 

premium.click();


111. Verifying Premium Is Selected

Assert.assertTrue(

    premium.isSelected(),

    "Premium option should be selected"

);


112. Verifying Other Options Are Not Selected

List<WebElement> plans = driver.findElements(

    By.cssSelector("input[name='plan']")

);

 

int selectedCount = 0;

 

for (WebElement plan : plans) {

    if (plan.isSelected()) {

        selectedCount++;

    }

}

 

Assert.assertEquals(

    selectedCount,

    1,

    "Only one plan should be selected"

);


113. Interview Question: How Do You Handle Radio Buttons in Selenium?

Locate the required radio button using a suitable locator and use click() to select it. The isSelected() method can be used to verify its current state.

WebElement radio = driver.findElement(By.id("male"));

 

if (!radio.isSelected()) {

    radio.click();

}


114. Interview Question: How Do You Check Whether a Radio Button Is Selected?

Use the isSelected() method.

boolean selected = radio.isSelected();


115. Interview Question: How Do You Select a Specific Radio Button From a Group?

Use a locator that uniquely identifies the required option, commonly by combining attributes such as name and value.

WebElement radio = driver.findElement(

    By.cssSelector(

        "input[name='payment'][value='upi']"

    )

);

 

radio.click();


116. Interview Question: How Do You Verify That Only One Radio Button Is Selected?

Find the radio buttons belonging to the group, iterate through them, count selected elements, and verify that the count matches the expected behavior.

List<WebElement> radios = driver.findElements(

    By.cssSelector("input[name='payment']")

);

 

int count = 0;

 

for (WebElement radio : radios) {

    if (radio.isSelected()) {

        count++;

    }

}

 

Assert.assertEquals(count, 1);


117. Interview Question: What Is the Difference Between Radio Buttons and Checkboxes?

Radio buttons are generally used for mutually exclusive choices within a group, while checkboxes are generally used for independent choices where multiple options may be selected.


118. Interview Question: Can Multiple Radio Buttons Be Selected?

Radio buttons that share the same name attribute are normally treated as one group, so only one should be selected at a time. Radio buttons with different names can belong to separate groups and can therefore have selections independently.


119. Interview Question: What Happens When You Click Another Radio Button in the Same Group?

The newly clicked option becomes selected and the previously selected option in the same radio group normally becomes unselected.


120. Interview Question: How Do You Select a Radio Button Based on Visible Text?

Locate the associated label using its text and then identify the corresponding input element.

WebElement radio = driver.findElement(

    By.xpath("//label[normalize-space()='Premium']/preceding-sibling::input")

);

 

radio.click();


121. Interview Question: What If the Radio Button Is Not Clickable?

First verify the locator, visibility, enabled state, page synchronization, overlays, iframe context, and custom UI implementation. Use an explicit wait when the radio button becomes available dynamically.


122. Interview Question: How Do You Handle a Hidden Radio Button?

Inspect the application's HTML and identify the visible control associated with the hidden radio input. If the application uses a label or custom control, interact with the appropriate visible element rather than unnecessarily forcing a click on a hidden input.


123. Practical Radio Button Automation Project

Create an automation test for a registration page containing:

  • Gender radio buttons
  • Account type radio buttons
  • Subscription plan radio buttons
  • Terms checkbox
  • Register button

Automation requirements:

  1. Open the registration page.
  2. Verify the default radio button states.
  3. Select the required gender.
  4. Select the required account type.
  5. Select the required subscription plan.
  6. Verify that only one option is selected in each group.
  7. Accept the required terms checkbox.
  8. Submit the form.
  9. Validate the resulting page.


124. Advanced Radio Button Automation Project

Create an e-commerce checkout automation framework containing payment and delivery radio button groups.

  • Select a payment method.
  • Select a delivery method.
  • Verify default selections.
  • Change the payment option.
  • Verify the previous payment option is deselected.
  • Change the delivery option.
  • Verify the final selections.
  • Submit the order.
  • Validate the confirmation page.
  • Execute the test through TestNG.
  • Generate test execution reports.


125. Radio Button Automation Best-Practice Summary

PracticeRecommendation
LocatorUse stable and unique locators.
GroupingUnderstand the name attribute and radio group structure.
SelectionUse click() to select the required option.
ValidationUse isSelected() to verify selection.
Enabled StateUse isEnabled() when disabled options are possible.
Dynamic UIUse explicit waits when elements appear dynamically.
Multiple OptionsUse findElements() when validating a complete group.
Custom ControlsUnderstand the visible control and underlying HTML.
IframeSwitch into the iframe before locating the element.
FrameworkUse reusable methods and Page Object Model.
AssertionsVerify the expected selection and group behavior.


126. Conclusion

Radio buttons are important Selenium WebDriver elements used when a web application requires the user to select one option from a group. Selenium provides methods such as click(), isSelected(), isDisplayed(), and isEnabled() for interacting with and validating radio buttons.

Effective radio button automation requires stable locators, a clear understanding of radio groups, correct handling of the name and value attributes, appropriate synchronization, and verification of the final selected state. Testers should also know how to handle custom controls, disabled elements, dynamic elements, tables, modals, iframes, and Shadow DOM.

For structured Selenium learning covering WebDriver, WebElements, locators, TestNG, automation frameworks, and practical testing, visit JustAcademy's Selenium Training Course. To explore the course demo registration option, visit Register for Course Demo.

whatsapp