Skip to content

How I can select an element from a dropdown list?

Problem: I try to select an element from a dropdown list

I have a dropdown list with the following HTML code:

<span class="wpcf7-form-control-wrap localitate">
<select name="localitate" class="wpcf7-form-control wpcf7-select form-control" id="cf_location_trigger" aria-invalid="false">
<option value="">Locatie</option>
<option value="Bucuresti CARAMFIL">Bucuresti CARAMFIL</option>
<option value="Bucuresti THE LIGHT">Bucuresti THE LIGHT</option>
<option value="Cluj-Napoca">Cluj-Napoca</option>
<option value="Iasi">Iasi</option></select></span>

I try to select the element with the following Java code but didn’t work:

 location.click();
   
   WebDriverWait waits = new WebDriverWait(driver, 20);
   waits.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id="cf_location_trigger"]"))).click();
           Select dropdownLocation = new Select(driver.findElement(By.xpath("//*[@id="cf_location_trigger"]")));
           dropdownLocation.selectByIndex(3);

How I can select the element,I tried to increase the time in Wait, I also tried with Thread.sleep () but it still doesn’t recognize the items in the list or dropdownLocation.selectByText("Bucuresti CARAMFI");

Answer

dropdownLocation.selectByText("Bucuresti");

I don’t see any option text as Bucuresti

try replacing with that :

Bucuresti CARAMFIL

Adding few more things :

waits.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id="cf_location_trigger"]"))).click();

You do not need to click on Select WebElement since it will be taken care by Select class that you have used.

You should use id, do not use ID with XPATH. until it’s necessary.

Something like this :

Select dropdownLocation = new Select(driver.findElement(By.id("cf_location_trigger")));

Update 1 :

Code in sequence :

Select dropdownLocation = new Select(driver.findElement(By.id("cf_location_trigger")));
dropdownLocation.selectByText("Bucuresti CARAMFI");

Udpate 2 :

WebDriverWait wait = new WebDriverWait(driver, 20);
Actions action = new Actions(driver);
action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("cf_location_trigger")))).build().perform();
Select select = new Select(wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("cf_location_trigger"))));
select.selectByVisibleText("Bucuresti CARAMFI");