7

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();
2
  • The id value of the two radio buttons are different then why can't you go for Id. Is there any specific reason? Commented Feb 13, 2013 at 9:07
  • id's for radio buttons are dynamically generated, so cannot locate by id Commented May 21, 2013 at 22:43

3 Answers 3

10

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();
Sign up to request clarification or add additional context in comments.

Comments

4

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();
        }
    }
}

Comments

1

Get the user input and assign to a variable called Usrinput

List<WebElement> radiobuttons = driver.findElements(By.name("radiobuttonname"));
    for(WebElement radiobutton: radiobuttons) { 

    if(radiobutton.getAttribute("value").equals("Usrinput"))
        radiobutton.click();
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.