Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Radio Buttons based on User Input in Selenium Webdriver

I want to be able to select a radio button based on User input. This radio button has multiple options with the same name.

<th class="radio">
 <td>
  <label for="form-1-input-3">
   <input id="form-1-input-3" type="radio" checked="" value="true" name="enabled">
   Enabled  
  </label>
  <label for="form-1-input-4">
   <input id="form-1-input-4" type="radio" value="false" name="enabled">
   Disabled  
  </label>

If "enabled" is passed as a string, I should be able to select the first radio button that has the visible text, Enabled and if "disabled" is passed as a string, I should be able to select radio button that has visible text, Disabled.

I am having difficulty since the name of the radio button is same. The below code fails to find the element with the AND operator for Xpath. Has anyone encountered this before and have found a solution?

String enableRadioButtonXPath = "//input[contains(@id,'form-') and contains(@value, 'enabled')]";
String enableRadioButtonOption = "enabled";
String disableRadioButtonOption = "disabled";

WebElement enableRadioButton = webdriver1.findElement(By.name(enableRadioButtonOption));
enableRadioButton.click();
like image 369
user1886649 Avatar asked Feb 13 '13 08:02

user1886649


2 Answers

This logic might be useful for you.

For selecting first radio button use below locator

 driver.findElement(By.xpath("//label[contains(.,'Enable')]/input")).click();

For selecting second radio button which has disable text

driver.findElement(By.xpath("//label[contains(.,'Disable')]/input")).click();
like image 93
Santoshsarma Avatar answered Nov 18 '22 00:11

Santoshsarma


Maybe this could help:

public void selectByName (final WebDriver driver, final String status) {
    final List<WebElement> radios = driver.findElements(By.name("enabled"));

    for (WebElement radio : radios) {
        if (radio.getText().equals(status)) {
            radio.click();
        }
    }
}
like image 26
aimbire Avatar answered Nov 18 '22 02:11

aimbire