How to check if the radio button is selected or not in Selenium WebDriver?

52,353

Solution 1

driver.findElement(By.id("26110162")).isSelected();

or

String str = driver.findElement(By.id("26110162")).getAttribute("checked");
if (str.equalsIgnoreCase("true"))
{
    System.out.println("Checkbox selected");
}

if the ID is changing... use the following XPATH:

//input[span='Seleccionar como tarjeta predeterminada']

or

//input[@name='address' and @type='radio']

Solution 2

.isSelected() function will returns you a boolean value True or False, depending on that you can check the condition and enable or leave the radio button selected.

driver.findElement(By.cssSelector("input[id='26110162']")).isSelected().

Declare a boolean value and store the result then provide an if condition to validate

Share:
52,353
user3538483
Author by

user3538483

Updated on July 09, 2022

Comments

  • user3538483
    user3538483 almost 2 years

    Here is my HTML code

    <div class="selectCard_left">
    <input id="26110162" class="default_shipping_address" type="radio" name="address" checked="true">
    <span>Seleccionar como tarjeta predeterminada</span> 
    

    I am trying with driver.findElement(By.id("17390233")).isSelected();, but I am not getting any value.