Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With webdriver.js, how to get the selected option of a <select>?

Plenty of answers for java and C#, but I can't find how to do it in javascript. Seems the API are different...

like image 501
Offirmo Avatar asked Dec 29 '25 17:12

Offirmo


2 Answers

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

like image 90
ChristianB Avatar answered Dec 31 '25 07:12

ChristianB


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');
   }
});
like image 29
nilesh Avatar answered Dec 31 '25 07:12

nilesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!