Reputation:
I'm trying to select a value from a small dropdown that appears to be a "ul" Here's what I see in Firebug:
<button class="btn btn-default dropdown-toggle" aria-expanded="true" aria-haspopup="true" data-toggle="dropdown" type="button">
<ul class="dropdown-menu">
<li>
<a href="javascript:void(0)">1</a>
</li>
<li>
<a href="javascript:void(0)">2</a>
</li>
<li>
<a href="javascript:void(0)">3</a>
Here's what I have so far, in Java:
public void selectPhoneType(String option)
{
driver.findElement(By.className("caret")).click();
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.className("dropdown-menu")));
WebElement element = driver.findElement()
}
Let's say I wanted to select/click on option "1". How would I complete my code? I haven't worked with "li" too much so I tried using a select, which obviously didnt work. Any help would be appreciated! Thanks
Upvotes: 2
Views: 23427
Reputation: 159
Try something like this:
public void selectPhoneType(String option) {
// Open the dropdown so the options are visible
driver.findElement(By.className("dropdown-menu")).click();
// Get all of the options
List<WebElement> options = driver.findElements(By.xpath("//ul[@class='dropdown-menu']/li"));
// Loop through the options and select the one that matches
for (WebElement opt : options) {
if (opt.getText().equals(option)) {
opt.click();
return;
}
}
throw new NoSuchElementException("Can't find " + option + " in dropdown");
}
Note: Selenium's Select() won't work here because your list is not under a 'select' tag.
Upvotes: 4
Reputation:
Another approach which parameterizes the selector.
This returns all 3 options:
$$("ul.dropdown-menu>li:eq a")
This adds a parameter to select which in the list you want:
$$("ul.dropdown-menu>li:nth-child(1) a")
Then you can map for your tests the child number and pass it into the selector:
1 = whatever
2 = whatever
3 = whatever
public void By someDroplist(String selection)
{
return By.cssSelector("ul.dropdown-menu>li:nth-child(" + selection + ") a");
}
Upvotes: 1
Reputation: 2703
driver.FindElement(By.XPath("//ul[@class='dropdown-menu']/li/a")).Click();
Upvotes: 0
Reputation: 1128
Based on how it's selected in the application you either should simulate mouse click with element.click()
or simulate keydown/keyup event with element.sendKeys(Keys.ENTER);
Also be aware that touch events may handle differently by your application (click may not work)
Here's a similar question
Upvotes: 0