I have a dropdown box that I would like to select a value using WebDriverJS. I\'ve looked at the user guide below and could not find out how to do it
driver.findElement({id: 'myDropDown'});// select dropdown element you wish to select
driver.sleep(1000);//not necessary
driver.findElement({id: 'myDropDown'}).sendKeys('name_of_option');//sending keys automatically fills dropdown with desired option
Sending keys to the dropdown element would be sufficient in this case, like;
driver.findElement(by.id('vote')).sendKeys('5');
When there is a space in the display text, webdriver needs to focus more so just adding click functions would solve it;
var ddlElement = driver.findElement(by.id('vote'));
ddlElement.click();
ddlElement.sendKeys('5');
ddlElement.click();
Certain browsers were being very difficult with dropdowns. I got some ideas and pieced together a java method using JS injection that might work for some of you who come across this. Yes, the issues are being fixed over time, but this is useful for those who are tasked with certifying older browsers. I hope this helps, because this can be very frustrating!
public void getJSDropdown(String dropDown, String elementID)throws Exception{
JavascriptExecutor executor = (JavascriptExecutor)driver;
String dropdownScript = "var select = window.document.getElementById('" +
dropDown +
"'); for(var i = 0; i < select.options.length; i++){if(select.options[i].text == '" +
elementID +
"'){ select.options[i].selected = true; } }";
Thread.sleep(2000);
executor.executeScript(dropdownScript);
Thread.sleep(2000);
String clickScript = "if ("+"\"createEvent\""+" in document) {var evt = document.createEvent("+"\"HTMLEvents\""+"); evt.initEvent("+"\"change\""+", false, true); " + dropDown + ".dispatchEvent(evt); } else " + dropDown + ".fireEvent("+"\"onchange\""+");";
executor.executeScript(clickScript);
}
This will work for me (coffeescript)
selectList.findElements(By.tagName("option")) =
.then (options) ->
len = options.length #getting number of options in the select
driver.wait => #verify all promises finished
for option in options
option.getText()
.then (text) =>
console.log(len)
len -= 1
console.log(text)
if len is 0
true
, 10000
use xpath like that
await driver.findElement(By.xpath('//[@id="newEventOffices"]/option[3]')).click();
You don't need two clicks to select an option, just click on the option directly. Something like,
driver.findElement(wd.By.css('#month>option[title=\'November\']')).click();