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 switch has several 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 switch that has visible text, Enabled, and if "disabled" is passed as a string, I should select a switch that has visible text, disabled.

I am having difficulty because the switch name is the same. The code below cannot find an element with an AND operator for Xpath. Has anyone come across this before and 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(); 
+7
source share
3 answers

This logic may be useful to you.

To select the first switch, use below the locator

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

To select a second radio button that disables text

 driver.findElement(By.xpath("//label[contains(.,'Disable')]/input")).click(); 
+9
source

Perhaps 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(); } } } 
+4
source

Get user input and assign a variable named Usrinput

 List<WebElement> radiobuttons = driver.findElements(By.name("radiobuttonname")); for(WebElement radiobutton: radiobuttons) { if(radiobutton.getAttribute("value").equals("Usrinput")) radiobutton.click(); } 
+1
source

All Articles