1

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

1
  • If one of these answers helped you, please select one. Commented Oct 20, 2021 at 18:53

2 Answers 2

1

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

Comments

0

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

2 Comments

.equalsIgnoreCase I didn't know. One learns every day :-)
I know right? I love that feeling of finding a new method! Glad I was able to help show you something new!

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.