skip to Main Content

I am trying to verify if my radio button is selected or not, but each time I am getting value as false even when I select the radio button.

HTML page

<div class="controls tss-radio-text-format">
   <label class="tss-radio">
   <input type="radio" name="answer_check" id="answer_check-true" value="true" checked="">
   <span class="radiobutton">
   </span><span class="tss-label">Yes</span></label><label class="tss-radio">
   <input type="radio" name="answer_check" id="answer_check-false" value="false">
   <span class="radiobutton"></span>
   <span class="tss-label">No</span></label>
</div>

Below is the code that I tried to click on radio button and verify if radio button Yes is selected.
The output I get is false but I was expecting true and I see Yes radio button was selected in the chrome browser I am using

public void clickAndVerifySelection() throws InterruptedException {
  driver.findElement(By.xpath("(//span[@class='radiobutton'])[1] ")).click();
  Thread.sleep(2000);
  boolean value = driver.findElement(By.xpath("(//span[@class='radiobutton'])[1] ")).isSelected();
  System.out.println(value);
}

2

Answers


  1. isSelected() will work only on the input tag
    You need to take xpath like //input[name='answer_check']

    Login or Signup to reply.
  2. isSelected()

    isSelected() returns a boolean determining whether the element is selected or not. This operation only applies to <input> elements such as checkboxes, options in a select and radio buttons.


    Solution

    To validate if the <input> associated with Yes is selected or not you can use either of the following strategies:

    • Using id attribute:

      driver.findElement(By.xpath("//span[@class='tss-label' and text()='Yes']//preceding-sibling::input[contains(@id, 'true')]"));
      
    • Using value attribute:

      driver.findElement(By.xpath("//span[@class='tss-label' and text()='Yes']//preceding-sibling::input[@value='true']"));
      
    • Using checked attribute:

      driver.findElement(By.xpath("//span[@class='tss-label' and text()='Yes']//preceding-sibling::input[checked]"));
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search