Plenty of answers for java and C#, but I can't find how to do it in javascript. Seems the API are different...
yeah it is possible. Lets say we have the following select element:
<select name="test" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You get the current selected option by using getValue and you can change the selection by using click. Here is an simple example:
var webdriverjs = require('webdriverjs'),
client = webdriverjs.remote({desiredCapabilities:{browserName:'phantomjs'}}).init();
client
.url('http://localhost:8080')
.getValue('#select',function(err,val){
console.log(val); // will output "1"
})
.click('//*[@id="select"]/option[3]')
.getValue('#select',function(err,val){
console.log(val); // will output "3"
})
.end();
Hope that helps.
cheers
For those who are just looking for pure WebDriverJS solution and not any framework specific like webdriver.io or protractor, here is the code,
var element = driver.findElement(wd.By.id('mySelect'));
element.getAttribute('value').then(function(selected) {
if(selected === 'the one I expected') {
done();
}
else {
done(new Error('something went wrong');
}
});
If you want the option element, use the return value of then
callback:
driver.findElement(By.css('select[name=eventTypes]'))
.then((select) => {
return select.getAttribute('value').then((value) => {
return {select: select, value: value};
});
})
.then((data) => {
return data.select.findElement(By.css('option[value="'+data.value+'"]'));
})
.then((option) => {
//do something.
});
If you have this in your html for an example
<select name="test" id="myId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You can select for a example option 3 like this
var driver = new firefox.Driver();
driver.findElement(By.css('#myId>option:nth-child(2)')).click();
Works for me and I am using selenium-webdriver with JavaScript
Although the question has been posted for 7 years, I would like to share my answer that works now. You can get the selected option/value by
let select_value = await driver.findElement(By.css('select')).getAttribute('value')
I did using this
element=await driver.findElement(By.name("quantity")); // here you have to select your element suppose i am using get element by name
// below will help you to get selected value from select option
var SelectedValue=element.getAttribute('value').then(function(selected) { return selected;});
© 2022 - 2024 — McMap. All rights reserved.