2

I am having hard time with identifying if radio option No is selected or not using Selenium Java. Below is the screenshot of the radio options on the web page. A workable solution is much appreciated.

enter image description here

Below is the HTML code. ::after (highlighted below) gets dynamically loaded when No option is selected.

enter image description here

I created below Java method that executes JavaScript that I am expecting to return whole label tag. It is currently printing out null. However, when I execute the script used below in Chrome browser console, it identifies the entire label tag including ::before and ::after pseudo elements.

public String whichRadioOptionIsSelected() {
        String tag = "";
        List<WebElement> radioOptions = findElementsByXpath(".//div[@id='ButtonOptions']/label");

        for(int i = 1; i <= radioOptions.size(); i++) {
                String script = "return document.querySelector('div#ButtonOptions > label:nth-of-type("+i+") label', null);";
                JavascriptExecutor js = (JavascriptExecutor) driver;
                tag = (String) js.executeScript(script);
                System.out.println(tag);
            }        
        return tag;
    }
4
  • what happens when u use isSelected() on input tag
    – PDHide
    Commented Jun 28, 2020 at 17:00
  • Hello @PDHide, I created a separate method that used isSelected() and it always returned 'false'. Here is the code that I tried: java public boolean whichRadioOptionSelected() { boolean isNoSelected = false; if (isElementPresent(conditionTrue)) { WebElement noOption = findElementByXpath(RADIO_NO); if (noOption.isSelected()) { isNoSelected = true; } else { isNoSelected = false; } } return isNoSelected; }
    – skota
    Commented Jun 28, 2020 at 19:26
  • why to create separe method when u already have inbuilt method
    – PDHide
    Commented Jun 28, 2020 at 21:34
  • What was the xpath in radio_no
    – PDHide
    Commented Jun 28, 2020 at 22:07

1 Answer 1

1

Try this:

public String whichRadioOptionIsSelected() {
        try {
            WebElement selectedOption = findElementByXpath("//div[@id='ButtonOptions']//input[@value='true']/following-sibling::label");
            if(selectedOption.isPresent())
                return selectedOption.getText();
        }
        catch(Exception e) {
            return null;
        }       
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.