How to select individual dynamic options of a multi-select through Selenium and Java

Hi I am trying to automate the process where my script will select individual values in the multi-select box and perform some action based on the results. Below is my code. problem with my code is, it will select all the values of a multi-select, instead it should select individual item in the list. All the list values are dynamic in nature and we can't predict what is coming. Requesting your help in this regard!

Values in the multi select are Test 1, Test 2 and so on.

public void filterByTemplateName() throws Exception 
{
    WebDriverWait wait = new WebDriverWait(driver, 15);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("performing action")));
    WebElement eventName = driver.findElement(By.xpath(".//select[@name='Test_templateName']']")); 
    driver.switchTo().frame("test_frame");
    Select sel = new Select(templateName);
    List<WebElement> options = sel.getOptions();
    for (WebElement temp:options) 
    {
        temp.click(); 
    } 
}

2 answers

  • answered 2019-03-14 04:38 C. Peck

    Since you've initialized this sel variable as a Select object you should be able to use the methods that Select provides for this:

    for (WebElement temp:options) {
        sel.selectByVisibleText(temp);
    }
    

    Does that help?

  • answered 2019-03-14 08:02 DebanjanB

    Considering all of your test criteria of:

    • Selecting individual item from the list of the multi-select one by one through an iteration.
    • List values are dynamic.
    • You can't predict what is coming.

    To select individual item from the list you can use the following solution:

    WebElement dropdown_element = driver.findElement(By.xpath("xpath_dropdown_element"));
    Select templateName = new Select(dropdown_element);
    List<WebElement> options = templateName.getOptions();
    for(int i=0; i<options.size(); i++)
    {
        new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("./dropdown_element//options"))).get(i).click();
        System.out.println("You can perform your other task for this option selection");
    }