How to handle radio button in selenium Webdriver

asked 3 months ago

There are different operations we can perform on the radio button using Selenium web driver.

Most operations are:

          - To select the radio button

         -  To determine which Radio button is selected

Navigate to https://www.qafeast.com/demo, and click the radio button tab.

Press F12 on the keyboard and inspect the radio button.

 

 

Select the radio button:

Selenium webdriver doesn't provide a special method to select the radio button, we can use the click() method to select the radio button.

Syntax:

driver.findElement(By.locator).click();

 

Example:

driver.findElement(By.xpath("//label[text()='Male']")).click();

 

To check which one is selected:

isSelected() function is used to know which radio button is Selected. isSelected() function return the boolean value.

Syntax:

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

 

Example:

boolean rdBtn = driver.findElement(By.xpath("//input[@value='Male is selected']")).isSelected();
if (rdBtn)
{
    System.out.println("Male is selected");
}
else
{
    System.out.println("Male is not selected");
}
 

 

Using getAttribute() function we can determine using the checked property

String rdBt = driver.findElement(By.xpath("//input[@value='Female is selected']")).getAttribute("checked");
System.out.println(rdBt);

 

If the Radio button is selected, then it returns true otherwise, it returns false.

 

Using Selenium Csharp

 

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ConsoleApp1
{
    internal class SeleniumTest
    {
        static IWebDriver driver;
        static void Main(string[] args)
        {
           
            driver = new ChromeDriver(@"\\Driver\\chromedriver.exe");
            //Implicit Wait:
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
            driver.Navigate().GoToUrl("https://qafeast.com/demo");
            driver.FindElement(By.XPath("//label[text()='Radio Button']")).Click();
            //Select the radio button:
            driver.FindElement(By.XPath("//label[text()='Male']")).Click();
            //To check which one is selected:
            bool rdBtn = driver.FindElement(By.XPath("//input[@value='Male is selected']")).Selected;
            if (rdBtn)
            {
                Console.WriteLine("Male is selected");
            }
            else
            {
                Console.WriteLine("Male is not selected");
            }
            //Using getAttribute() function we can determine using the checked property
            string rdBt = driver.FindElement(By.XPath("//input[@value='Female is selected']")).GetAttribute("class");
           Console.WriteLine(rdBt);
            driver.Quit();  
        }
    }
}