Popular Searches
Popular Course Categories
Popular Courses

Radio Buttons

HTML & Web Elements

<div class="selenium-notes">

<h1>Radio Buttons in Selenium</h1>

<p>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 <code>click()</code>, <code>isSelected()</code>, <code>isDisplayed()</code>, and <code>isEnabled()</code>.</p>

<p>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.</p>

<p>Selenium training commonly covers WebElements, forms, browser interactions, locators, and automation frameworks. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Learn more about Selenium Training</a> and <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for a Course Demo</a>.</p>

<hr>

<h2>1. What is a Radio Button?</h2>

<p>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 <code>name</code> attribute.</p>

<pre><code>&lt;input type="radio" name="gender" value="male"&gt; Male

&lt;input type="radio" name="gender" value="female"&gt; Female

&lt;input type="radio" name="gender" value="other"&gt; Other</code></pre>

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

<hr>

<h2>2. Why Radio Buttons are Important in Automation Testing</h2>

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

<ul>

<li>Selecting gender</li>

<li>Selecting payment methods</li>

<li>Choosing delivery methods</li>

<li>Selecting account types</li>

<li>Choosing subscription plans</li>

<li>Selecting shipping options</li>

<li>Choosing employment status</li>

<li>Selecting Yes or No options</li>

<li>Choosing preferred language</li>

<li>Selecting booking preferences</li>

</ul>

<hr>

<h2>3. Basic HTML Structure of a Radio Button</h2>

<pre><code>&lt;input type="radio" id="male" name="gender" value="male"&gt;

&lt;label for="male"&gt;Male&lt;/label&gt;</code></pre>

<p>Important attributes include:</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Attribute</th><th>Purpose</th></tr>

<tr><td>type</td><td>Defines the input as a radio button.</td></tr>

<tr><td>id</td><td>Provides a unique identifier.</td></tr>

<tr><td>name</td><td>Groups related radio buttons.</td></tr>

<tr><td>value</td><td>Represents the value submitted by the form.</td></tr>

<tr><td>class</td><td>Provides CSS-based identification or styling.</td></tr>

<tr><td>checked</td><td>Indicates the default selected option.</td></tr>

<tr><td>disabled</td><td>Prevents interaction with the radio button.</td></tr>

</table>

<hr>

<h2>4. Radio Button Group</h2>

<p>A radio button group normally contains multiple radio buttons with the same <code>name</code> attribute.</p>

<pre><code>&lt;input type="radio" name="payment" value="card"&gt; Credit Card

&lt;input type="radio" name="payment" value="upi"&gt; UPI

&lt;input type="radio" name="payment" value="cash"&gt; Cash</code></pre>

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

<hr>

<h2>5. Radio Button vs Checkbox</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Radio Button</th><th>Checkbox</th></tr>

<tr><td>Normally used to select one option from a group.</td><td>Can normally be used to select multiple independent options.</td></tr>

<tr><td>Options are usually mutually exclusive.</td><td>Options can usually be selected independently.</td></tr>

<tr><td>Commonly grouped using the same name.</td><td>Each checkbox can represent an independent choice.</td></tr>

<tr><td>Example: Male/Female/Other.</td><td>Example: Java/Selenium/SQL.</td></tr>

</table>

<hr>

<h2>6. Setting Up Selenium for Radio Button Testing</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>7. Locating a Radio Button Using ID</h2>

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

<pre><code>WebElement maleRadio = driver.findElement(By.id("male"));

maleRadio.click();</code></pre>

<hr>

<h2>8. Locating a Radio Button Using Name</h2>

<pre><code>WebElement radio = driver.findElement(By.name("gender"));

radio.click();</code></pre>

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

<hr>

<h2>9. Locating a Radio Button Using Class Name</h2>

<pre><code>WebElement radio = driver.findElement(

    By.className("gender-radio")

);

 

radio.click();</code></pre>

<p>Class Name should be used carefully if multiple elements share the same class.</p>

<hr>

<h2>10. Locating a Radio Button Using Tag Name</h2>

<pre><code>WebElement radio = driver.findElement(By.tagName("input"));

radio.click();</code></pre>

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

<hr>

<h2>11. Locating a Radio Button Using CSS Selector</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>12. CSS Selector Using ID</h2>

<pre><code>WebElement radio = driver.findElement(

    By.cssSelector("#male")

);

 

radio.click();</code></pre>

<hr>

<h2>13. CSS Selector Using Name and Value</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<p>This is useful when several radio buttons belong to the same group.</p>

<hr>

<h2>14. CSS Selector Using Multiple Attributes</h2>

<pre><code>WebElement radio = driver.findElement(

    By.cssSelector(

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

    )

);

 

radio.click();</code></pre>

<hr>

<h2>15. Locating Radio Button Using XPath</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>16. XPath Using ID</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>17. XPath Using Name</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>18. XPath Using Value</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>19. XPath Using Multiple Attributes</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>20. XPath Using Label Text</h2>

<p>Sometimes the radio input has limited identifying information while the associated label contains meaningful text.</p>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>21. Using the click() Method</h2>

<p>The <code>click()</code> method is used to select a radio button.</p>

<pre><code>WebElement radio = driver.findElement(By.id("male"));

radio.click();</code></pre>

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

<hr>

<h2>22. Understanding isSelected()</h2>

<p>The <code>isSelected()</code> method checks whether a radio button is currently selected.</p>

<pre><code>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");

}</code></pre>

<hr>

<h2>23. Checking Radio Button Visibility</h2>

<pre><code>WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isDisplayed()) {

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

}</code></pre>

<hr>

<h2>24. Checking Radio Button Enabled State</h2>

<pre><code>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");

}</code></pre>

<hr>

<h2>25. Complete Radio Button State Validation</h2>

<pre><code>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());</code></pre>

<hr>

<h2>26. Select Radio Button Only If It Is Not Selected</h2>

<p>Checking the current state before clicking makes the automation more predictable.</p>

<pre><code>WebElement radio = driver.findElement(By.id("male"));

 

if (!radio.isSelected()) {

    radio.click();

}</code></pre>

<hr>

<h2>27. Verify Radio Button Is Selected</h2>

<pre><code>WebElement radio = driver.findElement(By.id("male"));

 

radio.click();

 

if (radio.isSelected()) {

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

}</code></pre>

<hr>

<h2>28. Verify Radio Button Is Not Selected</h2>

<pre><code>WebElement radio = driver.findElement(By.id("female"));

 

if (!radio.isSelected()) {

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

}</code></pre>

<hr>

<h2>29. Selecting One Option From a Radio Group</h2>

<pre><code>WebElement upi = driver.findElement(

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

);

 

if (!upi.isSelected()) {

    upi.click();

}</code></pre>

<hr>

<h2>30. Multiple Radio Buttons</h2>

<p>A page can contain several radio buttons belonging to different groups.</p>

<pre><code>&lt;input type="radio" name="gender" value="male"&gt; Male

&lt;input type="radio" name="gender" value="female"&gt; Female

 

&lt;input type="radio" name="payment" value="card"&gt; Card

&lt;input type="radio" name="payment" value="upi"&gt; UPI</code></pre>

<p>There are two separate groups here: <code>gender</code> and <code>payment</code>.</p>

<hr>

<h2>31. Finding Multiple Radio Buttons</h2>

<pre><code>List&lt;WebElement&gt; radios = driver.findElements(

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

);</code></pre>

<hr>

<h2>32. Counting Radio Buttons</h2>

<pre><code>List&lt;WebElement&gt; radios = driver.findElements(

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

);

 

System.out.println("Total radio buttons: " + radios.size());</code></pre>

<hr>

<h2>33. Import Required for List</h2>

<pre><code>import java.util.List;</code></pre>

<hr>

<h2>34. Selecting a Specific Radio Button by Value</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>35. Selecting a Specific Radio Button by Label</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>36. Selecting Radio Button Based on User Choice</h2>

<pre><code>String expectedOption = "UPI";

 

WebElement radio = driver.findElement(

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

);

 

if (!radio.isSelected()) {

    radio.click();

}</code></pre>

<hr>

<h2>37. Selecting Radio Button Using a Dynamic XPath</h2>

<pre><code>String option = "Credit Card";

 

WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>38. XPath contains() for Dynamic Radio Button</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>39. XPath starts-with() for Dynamic Radio Button</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>40. Handling a Pre-Selected Radio Button</h2>

<p>A radio button may already be selected when the page loads.</p>

<pre><code>WebElement radio = driver.findElement(By.id("male"));

 

if (radio.isSelected()) {

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

} else {

    radio.click();

}</code></pre>

<hr>

<h2>41. Handling Disabled Radio Button</h2>

<p>A disabled radio button cannot normally be selected through standard user interaction.</p>

<pre><code>WebElement radio = driver.findElement(By.id("premium"));

 

if (radio.isEnabled()) {

    radio.click();

} else {

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

}</code></pre>

<hr>

<h2>42. Handling Radio Button With Label</h2>

<pre><code>&lt;input type="radio" id="card" name="payment" value="card"&gt;

&lt;label for="card"&gt;Credit Card&lt;/label&gt;</code></pre>

<p>The label is associated with the radio button through the <code>for</code> attribute.</p>

<hr>

<h2>43. Clicking the Label Instead of Radio Button</h2>

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

<pre><code>WebElement label = driver.findElement(

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

);

 

label.click();</code></pre>

<hr>

<h2>44. Custom Styled Radio Button</h2>

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

<pre><code>&lt;input type="radio" id="online" name="delivery" hidden&gt;

&lt;label for="online" class="custom-radio"&gt;

    Online Delivery

&lt;/label&gt;</code></pre>

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

<hr>

<h2>45. Hidden Radio Button</h2>

<pre><code>WebElement radio = driver.findElement(By.id("online"));

 

System.out.println("Displayed: " + radio.isDisplayed());</code></pre>

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

<hr>

<h2>46. ElementClickInterceptedException</h2>

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

<pre><code>try {

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

    radio.click();

} catch (ElementClickInterceptedException e) {

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

}</code></pre>

<hr>

<h2>47. ElementNotInteractableException</h2>

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

<pre><code>try {

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

    radio.click();

} catch (ElementNotInteractableException e) {

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

}</code></pre>

<hr>

<h2>48. NoSuchElementException</h2>

<p>If Selenium cannot locate the required radio button, <code>NoSuchElementException</code> may occur.</p>

<pre><code>try {

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

    radio.click();

} catch (NoSuchElementException e) {

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

}</code></pre>

<hr>

<h2>49. StaleElementReferenceException</h2>

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

<pre><code>try {

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

    radio.click();

} catch (StaleElementReferenceException e) {

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

}</code></pre>

<hr>

<h2>50. Waiting for Radio Button Visibility</h2>

<p>Dynamic applications may display radio buttons after page loading or after another user action.</p>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement radio = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("male")

    )

);</code></pre>

<hr>

<h2>51. Waiting for Radio Button to Become Clickable</h2>

<pre><code>WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement radio = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("male")

    )

);

 

radio.click();</code></pre>

<hr>

<h2>52. Implicit Wait for Radio Button</h2>

<pre><code>driver.manage().timeouts().implicitlyWait(

    Duration.ofSeconds(10)

);

 

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

radio.click();</code></pre>

<hr>

<h2>53. Explicit Wait vs Implicit Wait</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Implicit Wait</th><th>Explicit Wait</th></tr>

<tr><td>Applies to element searches globally.</td><td>Targets a specific condition.</td></tr>

<tr><td>Configured once.</td><td>Configured where required.</td></tr>

<tr><td>Useful for general synchronization.</td><td>Useful for dynamic UI conditions.</td></tr>

<tr><td>Less specific.</td><td>More condition-specific.</td></tr>

</table>

<hr>

<h2>54. Selecting Radio Button With JavaScript</h2>

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

<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;

 

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

 

js.executeScript("arguments[0].click();", radio);</code></pre>

<hr>

<h2>55. Checking Radio Button State With JavaScript</h2>

<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;

 

Boolean selected = (Boolean) js.executeScript(

    "return arguments[0].checked;",

    radio

);

 

System.out.println("Selected: " + selected);</code></pre>

<hr>

<h2>56. When Not to Use JavaScript Click</h2>

<ul>

<li>Do not use JavaScript click as the first solution.</li>

<li>Verify the locator first.</li>

<li>Check whether the radio button is visible.</li>

<li>Check whether the radio button is enabled.</li>

<li>Check whether an overlay is blocking it.</li>

<li>Use explicit waits when synchronization is the actual problem.</li>

<li>Use JavaScript only when the application's UI structure requires it.</li>

</ul>

<hr>

<h2>57. Radio Buttons in a Registration Form</h2>

<pre><code>&lt;form&gt;

    &lt;input type="radio" name="gender" value="male"&gt; Male

    &lt;input type="radio" name="gender" value="female"&gt; Female

    &lt;input type="radio" name="gender" value="other"&gt; Other

    &lt;button type="submit"&gt;Register&lt;/button&gt;

&lt;/form&gt;</code></pre>

<hr>

<h2>58. Automating Gender Selection</h2>

<pre><code>WebElement female = driver.findElement(

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

);

 

if (!female.isSelected()) {

    female.click();

}</code></pre>

<hr>

<h2>59. Verifying Gender Selection</h2>

<pre><code>WebElement female = driver.findElement(

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

);

 

female.click();

 

if (female.isSelected()) {

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

}</code></pre>

<hr>

<h2>60. Testing Mutually Exclusive Behavior</h2>

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

<pre><code>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());</code></pre>

<hr>

<h2>61. Radio Button Group Validation</h2>

<pre><code>List&lt;WebElement&gt; 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);</code></pre>

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

<hr>

<h2>62. Verify Only One Radio Button Is Selected</h2>

<pre><code>Assert.assertEquals(

    selectedCount,

    1,

    "Exactly one radio button should be selected"

);</code></pre>

<hr>

<h2>63. Verify No Radio Button Is Selected</h2>

<p>Some optional radio groups may initially have no selection.</p>

<pre><code>Assert.assertEquals(

    selectedCount,

    0,

    "No radio button should be selected initially"

);</code></pre>

<hr>

<h2>64. Verify Default Radio Button</h2>

<pre><code>WebElement defaultOption = driver.findElement(

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

);

 

Assert.assertTrue(

    defaultOption.isSelected(),

    "Standard delivery should be selected by default"

);</code></pre>

<hr>

<h2>65. Selecting Payment Method</h2>

<pre><code>WebElement card = driver.findElement(

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

);

 

if (!card.isSelected()) {

    card.click();

}</code></pre>

<hr>

<h2>66. Selecting Delivery Method</h2>

<pre><code>WebElement express = driver.findElement(

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

);

 

express.click();</code></pre>

<hr>

<h2>67. Selecting Subscription Plan</h2>

<pre><code>WebElement premium = driver.findElement(

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

);

 

premium.click();</code></pre>

<hr>

<h2>68. Selecting Yes/No Radio Buttons</h2>

<pre><code>WebElement yes = driver.findElement(

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

);

 

yes.click();</code></pre>

<hr>

<h2>69. Handling Radio Buttons by Label Text</h2>

<pre><code>String option = "Premium";

 

WebElement radio = driver.findElement(

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

);

 

if (!radio.isSelected()) {

    radio.click();

}</code></pre>

<hr>

<h2>70. Radio Button Inside a Table</h2>

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

<pre><code>&lt;table&gt;

    &lt;tr&gt;

        &lt;td&gt;

            &lt;input type="radio" name="product" value="101"&gt;

        &lt;/td&gt;

        &lt;td&gt;Laptop&lt;/td&gt;

    &lt;/tr&gt;

    &lt;tr&gt;

        &lt;td&gt;

            &lt;input type="radio" name="product" value="102"&gt;

        &lt;/td&gt;

        &lt;td&gt;Tablet&lt;/td&gt;

    &lt;/tr&gt;

&lt;/table&gt;</code></pre>

<hr>

<h2>71. Select Radio Button for a Specific Table Row</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>72. Radio Button in a Product Listing</h2>

<pre><code>WebElement product = driver.findElement(

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

);

 

product.click();</code></pre>

<hr>

<h2>73. Radio Button Inside a Modal</h2>

<pre><code>WebElement modal = driver.findElement(By.id("settingsModal"));

 

WebElement radio = modal.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>74. Radio Button Inside an Iframe</h2>

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

<pre><code>WebElement frame = driver.findElement(

    By.id("paymentFrame")

);

 

driver.switchTo().frame(frame);

 

WebElement radio = driver.findElement(

    By.id("card")

);

 

radio.click();

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>75. Radio Button Inside Nested Iframes</h2>

<pre><code>driver.switchTo().frame("outerFrame");

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

 

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

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>76. Radio Button in Shadow DOM</h2>

<p>Modern web components may place radio buttons inside a Shadow DOM.</p>

<pre><code>WebElement host = driver.findElement(

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

);

 

SearchContext shadowRoot = host.getShadowRoot();

 

WebElement radio = shadowRoot.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>77. Radio Button in a Dynamic List</h2>

<pre><code>WebElement option = driver.findElement(

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

);

 

WebElement radio = option.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>78. Dynamic Radio Button IDs</h2>

<p>Some applications generate IDs dynamically.</p>

<pre><code>&lt;input type="radio" id="option_827361" name="plan" value="premium"&gt;</code></pre>

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

<hr>

<h2>79. Handling Radio Button With Dynamic Value</h2>

<pre><code>String value = "premium";

 

WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>80. Radio Button Automation Flow</h2>

<pre><code>Start

  |

  v

Open Web Page

  |

  v

Locate Radio Button

  |

  v

Is Element Present?

  |

  +---- No ----&gt; Handle Locator/Error

  |

 Yes

  |

  v

Is Radio Button Enabled?

  |

  +---- No ----&gt; Verify Disabled State

  |

 Yes

  |

  v

Check Current Selection

  |

  +---- Selected ----&gt; Continue

  |

  +---- Not Selected ----&gt; Click

  |

  v

Verify Selected State

  |

  v

Verify Group Behavior

  |

  v

Continue Test

  |

  v

End</code></pre>

<hr>

<h2>81. Common Radio Button Test Scenarios</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Scenario</th><th>Expected Result</th></tr>

<tr><td>Radio button is visible</td><td>Radio button should be displayed.</td></tr>

<tr><td>Radio button is enabled</td><td>User should be able to select it.</td></tr>

<tr><td>Radio button is disabled</td><td>User should not be able to select it.</td></tr>

<tr><td>Radio button is selected</td><td><code>isSelected()</code> should return true.</td></tr>

<tr><td>Radio button is not selected</td><td><code>isSelected()</code> should return false.</td></tr>

<tr><td>Another option is selected</td><td>Previous selection should change according to the radio group behavior.</td></tr>

<tr><td>Default option exists</td><td>Expected option should be selected on page load.</td></tr>

<tr><td>Required group is empty</td><td>Appropriate validation should appear.</td></tr>

<tr><td>Radio button is dynamically loaded</td><td>Automation should wait for the element.</td></tr>

<tr><td>Radio button is inside iframe</td><td>Automation should switch into the iframe.</td></tr>

</table>

<hr>

<h2>82. Radio Button Validation Checklist</h2>

<ul>

<li>Verify radio button visibility.</li>

<li>Verify radio button enabled state.</li>

<li>Verify default selection.</li>

<li>Verify selection behavior.</li>

<li>Verify mutually exclusive behavior.</li>

<li>Verify required-field validation.</li>

<li>Verify dynamic radio button behavior.</li>

<li>Verify custom styled radio buttons.</li>

<li>Verify radio buttons inside tables.</li>

<li>Verify radio buttons inside iframes.</li>

<li>Verify radio button behavior across supported browsers.</li>

</ul>

<hr>

<h2>83. Common Mistakes While Automating Radio Buttons</h2>

<ul>

<li>Using a broad locator that matches multiple radio buttons.</li>

<li>Ignoring the <code>name</code> grouping.</li>

<li>Using unstable dynamic IDs.</li>

<li>Clicking without checking the current state when state-sensitive logic is required.</li>

<li>Ignoring disabled state.</li>

<li>Ignoring visibility.</li>

<li>Ignoring synchronization issues.</li>

<li>Using JavaScript unnecessarily.</li>

<li>Forgetting to switch into an iframe.</li>

<li>Not verifying the final selection.</li>

</ul>

<hr>

<h2>84. Bad Radio Button Locator</h2>

<pre><code>driver.findElement(By.xpath("//input")).click();</code></pre>

<p>This locator is too broad and may select an unrelated input field.</p>

<hr>

<h2>85. Better Radio Button Locator</h2>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>86. Best Practices for Radio Button Automation</h2>

<ul>

<li>Use stable and unique locators.</li>

<li>Prefer ID when it is stable and unique.</li>

<li>Use CSS selectors or XPath when required.</li>

<li>Use the <code>name</code> attribute to understand radio groups.</li>

<li>Use <code>value</code> to distinguish options in the same group.</li>

<li>Use <code>isSelected()</code> to validate state.</li>

<li>Use <code>isEnabled()</code> before interaction when appropriate.</li>

<li>Use explicit waits for dynamic applications.</li>

<li>Verify the expected final selection.</li>

<li>Avoid unnecessary JavaScript execution.</li>

<li>Keep locators maintainable.</li>

<li>Use Page Object Model in larger automation frameworks.</li>

</ul>

<hr>

<h2>87. Real-World Example: Registration Form</h2>

<pre><code>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"

);</code></pre>

<hr>

<h2>88. Real-World Example: Payment Method</h2>

<pre><code>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"

);</code></pre>

<hr>

<h2>89. Real-World Example: Delivery Options</h2>

<pre><code>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()

);</code></pre>

<hr>

<h2>90. Real-World Example: Subscription Plan</h2>

<pre><code>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"

);</code></pre>

<hr>

<h2>91. TestNG Radio Button Validation</h2>

<pre><code>import static org.testng.Assert.assertTrue;

 

WebElement radio = driver.findElement(

    By.id("male")

);

 

radio.click();

 

assertTrue(

    radio.isSelected(),

    "Radio button should be selected"

);</code></pre>

<hr>

<h2>92. Complete TestNG Radio Button Test</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>93. Radio Button With Page Object Model</h2>

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

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>94. Reusable Radio Button Utility Method</h2>

<pre><code>public void selectRadioButton(By locator) {

    WebElement radio = driver.findElement(locator);

 

    if (!radio.isSelected()) {

        radio.click();

    }

}</code></pre>

<hr>

<h2>95. Reusable Radio Button Validation Method</h2>

<pre><code>public boolean isRadioButtonSelected(By locator) {

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

}</code></pre>

<hr>

<h2>96. Radio Button Utility With Explicit Wait</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>97. Selecting Radio Button From Multiple Options</h2>

<pre><code>List&lt;WebElement&gt; options = driver.findElements(

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

);

 

for (WebElement option : options) {

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

 

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

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>98. Finding Selected Radio Button From a Group</h2>

<pre><code>WebElement selectedOption = driver.findElement(

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

);

 

System.out.println(

    "Selected payment: " +

    selectedOption.getAttribute("value")

);</code></pre>

<hr>

<h2>99. CSS :checked Selector</h2>

<p>The CSS <code>:checked</code> pseudo-class can be useful for locating the currently selected radio button.</p>

<pre><code>WebElement selected = driver.findElement(

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

);

 

System.out.println(

    selected.getAttribute("value")

);</code></pre>

<hr>

<h2>100. Checking Whether a Radio Group Has a Selection</h2>

<pre><code>List&lt;WebElement&gt; 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");

}</code></pre>

<hr>

<h2>101. Counting Selected Radio Buttons</h2>

<pre><code>List&lt;WebElement&gt; selected = driver.findElements(

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

);

 

System.out.println(

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

);</code></pre>

<hr>

<h2>102. Verifying a Specific Value Is Selected</h2>

<pre><code>WebElement selected = driver.findElement(

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

);

 

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

 

Assert.assertEquals(

    actualValue,

    "upi",

    "UPI should be selected"

);</code></pre>

<hr>

<h2>103. Required Radio Group Validation</h2>

<p>Some forms require the user to select one option before submitting the form.</p>

<pre><code>&lt;input type="radio" name="delivery" value="standard" required&gt;

&lt;label&gt;Standard&lt;/label&gt;

 

&lt;input type="radio" name="delivery" value="express" required&gt;

&lt;label&gt;Express&lt;/label&gt;</code></pre>

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

<hr>

<h2>104. Radio Button Test Case Format</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case ID</th><th>Test Scenario</th><th>Expected Result</th></tr>

<tr><td>RAD001</td><td>Verify radio button visibility</td><td>Radio button should be visible.</td></tr>

<tr><td>RAD002</td><td>Verify radio button enabled state</td><td>Radio button should be enabled.</td></tr>

<tr><td>RAD003</td><td>Select radio button</td><td>Selected option should become active.</td></tr>

<tr><td>RAD004</td><td>Select another option</td><td>Previous option should be deselected within the same group.</td></tr>

<tr><td>RAD005</td><td>Verify default selection</td><td>Expected option should be selected initially.</td></tr>

<tr><td>RAD006</td><td>Verify required validation</td><td>Validation should appear when no option is selected.</td></tr>

<tr><td>RAD007</td><td>Verify disabled option</td><td>Disabled option should not be selectable.</td></tr>

<tr><td>RAD008</td><td>Verify dynamic radio button</td><td>Automation should wait and interact correctly.</td></tr>

</table>

<hr>

<h2>105. Radio Button Test Data Example</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Field</th><th>Possible Values</th><th>Expected Selection</th></tr>

<tr><td>Gender</td><td>Male, Female, Other</td><td>Female</td></tr>

<tr><td>Payment</td><td>Card, UPI, Cash</td><td>UPI</td></tr>

<tr><td>Delivery</td><td>Standard, Express</td><td>Express</td></tr>

<tr><td>Plan</td><td>Basic, Premium</td><td>Premium</td></tr>

<tr><td>Account Type</td><td>Personal, Business</td><td>Business</td></tr>

</table>

<hr>

<h2>106. Radio Button Automation With Logging</h2>

<pre><code>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()

);</code></pre>

<hr>

<h2>107. Radio Button Automation With Assertions</h2>

<pre><code>WebElement radio = driver.findElement(By.id("premium"));

 

if (!radio.isSelected()) {

    radio.click();

}

 

Assert.assertTrue(

    radio.isSelected(),

    "Premium radio button should be selected"

);</code></pre>

<hr>

<h2>108. Testing Radio Button Group Behavior</h2>

<pre><code>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());</code></pre>

<hr>

<h2>109. Radio Button Group With Three Options</h2>

<pre><code>&lt;input type="radio" name="plan" value="basic"&gt; Basic

&lt;input type="radio" name="plan" value="standard"&gt; Standard

&lt;input type="radio" name="plan" value="premium"&gt; Premium</code></pre>

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

<hr>

<h2>110. Selecting Premium From a Three-Option Group</h2>

<pre><code>WebElement premium = driver.findElement(

    By.cssSelector(

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

    )

);

 

premium.click();</code></pre>

<hr>

<h2>111. Verifying Premium Is Selected</h2>

<pre><code>Assert.assertTrue(

    premium.isSelected(),

    "Premium option should be selected"

);</code></pre>

<hr>

<h2>112. Verifying Other Options Are Not Selected</h2>

<pre><code>List&lt;WebElement&gt; 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"

);</code></pre>

<hr>

<h2>113. Interview Question: How Do You Handle Radio Buttons in Selenium?</h2>

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

<pre><code>WebElement radio = driver.findElement(By.id("male"));

 

if (!radio.isSelected()) {

    radio.click();

}</code></pre>

<hr>

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

<p>Use the <code>isSelected()</code> method.</p>

<pre><code>boolean selected = radio.isSelected();</code></pre>

<hr>

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

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

<pre><code>WebElement radio = driver.findElement(

    By.cssSelector(

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

    )

);

 

radio.click();</code></pre>

<hr>

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

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

<pre><code>List&lt;WebElement&gt; radios = driver.findElements(

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

);

 

int count = 0;

 

for (WebElement radio : radios) {

    if (radio.isSelected()) {

        count++;

    }

}

 

Assert.assertEquals(count, 1);</code></pre>

<hr>

<h2>117. Interview Question: What Is the Difference Between Radio Buttons and Checkboxes?</h2>

<p>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.</p>

<hr>

<h2>118. Interview Question: Can Multiple Radio Buttons Be Selected?</h2>

<p>Radio buttons that share the same <code>name</code> 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.</p>

<hr>

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

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

<hr>

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

<p>Locate the associated label using its text and then identify the corresponding input element.</p>

<pre><code>WebElement radio = driver.findElement(

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

);

 

radio.click();</code></pre>

<hr>

<h2>121. Interview Question: What If the Radio Button Is Not Clickable?</h2>

<p>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.</p>

<hr>

<h2>122. Interview Question: How Do You Handle a Hidden Radio Button?</h2>

<p>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.</p>

<hr>

<h2>123. Practical Radio Button Automation Project</h2>

<p>Create an automation test for a registration page containing:</p>

<ul>

<li>Gender radio buttons</li>

<li>Account type radio buttons</li>

<li>Subscription plan radio buttons</li>

<li>Terms checkbox</li>

<li>Register button</li>

</ul>

<p>Automation requirements:</p>

<ol>

<li>Open the registration page.</li>

<li>Verify the default radio button states.</li>

<li>Select the required gender.</li>

<li>Select the required account type.</li>

<li>Select the required subscription plan.</li>

<li>Verify that only one option is selected in each group.</li>

<li>Accept the required terms checkbox.</li>

<li>Submit the form.</li>

<li>Validate the resulting page.</li>

</ol>

<hr>

<h2>124. Advanced Radio Button Automation Project</h2>

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

<ul>

<li>Select a payment method.</li>

<li>Select a delivery method.</li>

<li>Verify default selections.</li>

<li>Change the payment option.</li>

<li>Verify the previous payment option is deselected.</li>

<li>Change the delivery option.</li>

<li>Verify the final selections.</li>

<li>Submit the order.</li>

<li>Validate the confirmation page.</li>

<li>Execute the test through TestNG.</li>

<li>Generate test execution reports.</li>

</ul>

<hr>

<h2>125. Radio Button Automation Best-Practice Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Locator</td><td>Use stable and unique locators.</td></tr>

<tr><td>Grouping</td><td>Understand the <code>name</code> attribute and radio group structure.</td></tr>

<tr><td>Selection</td><td>Use <code>click()</code> to select the required option.</td></tr>

<tr><td>Validation</td><td>Use <code>isSelected()</code> to verify selection.</td></tr>

<tr><td>Enabled State</td><td>Use <code>isEnabled()</code> when disabled options are possible.</td></tr>

<tr><td>Dynamic UI</td><td>Use explicit waits when elements appear dynamically.</td></tr>

<tr><td>Multiple Options</td><td>Use <code>findElements()</code> when validating a complete group.</td></tr>

<tr><td>Custom Controls</td><td>Understand the visible control and underlying HTML.</td></tr>

<tr><td>Iframe</td><td>Switch into the iframe before locating the element.</td></tr>

<tr><td>Framework</td><td>Use reusable methods and Page Object Model.</td></tr>

<tr><td>Assertions</td><td>Verify the expected selection and group behavior.</td></tr>

</table>

<hr>

<h2>126. Conclusion</h2>

<p>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 <code>click()</code>, <code>isSelected()</code>, <code>isDisplayed()</code>, and <code>isEnabled()</code> for interacting with and validating radio buttons.</p>

<p>Effective radio button automation requires stable locators, a clear understanding of radio groups, correct handling of the <code>name</code> and <code>value</code> 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.</p>

<p>For structured Selenium learning covering WebDriver, WebElements, locators, TestNG, automation frameworks, and practical testing, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a>. To explore the course demo registration option, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>

</div>

Previous Next
whatsapp