Home > Software engineering >  How do I click on radio button with dynamic input using selenium?
How do I click on radio button with dynamic input using selenium?

Time:10-20

I want to be able to click on either "Male" or "Female" option by inputing the value through a parameter

public void enter_gender_as(String gender) {

       
WebElement g = driver.findElement(By.cssSelector("input[value=(gender)]"));
g.click();
}

HTML snippet

CodePudding user response:

method:

public static void selectRadioButtonByValue(List<WebElement> radioButtons, String value) {
    for (WebElement radioButton: radioButtons) {
        if (radioButton.getAttribute("value").toLowerCase().equals(value.toLowerCase())) {
            radioButton.click();
            break;
        }
    }
}

usage:

List<WebElement> radioButtons = driver.findElements(By.id("gender"));
selectRadioButtonByValue(radioButtons, "male");

optionaly with WebDriver driver as argument:

public static void selectRadioButtonByValue(WebDriver driver, List<WebElement> radioButtons, String value) {
    for (WebElement radioButton: radioButtons) {
        if (radioButton.getAttribute("value").toLowerCase().equals(value.toLowerCase())) {
            radioButton.click();
            break;
        }
    }
}

selectRadioButtonByValue(driver, radioButtons, "male");

CodePudding user response:

You've got it, just write your code like this:

public void enter_gender_as(String gender) {
WebElement g = driver.findElement(By.cssSelector("input[value=("   gender   ")]"));
g.click();
}

Then call it correctly:

enter_gender_as("Male");

If you wanna get fancy then you can put ifs to check if the value isn't Male or Female. You can make gender .toLowerCase(). And you can add in an explicit wait, like an ExpectedCondition to wait for element to load. But this is the base functionality. Here's an example of what the "fancy" one would look like:

public void enter_gender_as(String gender) {
if(!gender.equalsIgnoreCase("Male") && !gender.equalsIgnoreCase("Female")){
System.out.println("Not a valid value! Please enter Male or Female");
}
WebElement g = driver.findElement(By.cssSelector("input[value=("   gender.toLowerCase   ")]"));
new WebDriverWait(driver, [int for timeout]).until(ExpectedConditions.visibilityOf(g));

g.click();
}
  • Related