Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting dropdown in WebDriverJs

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

https://code.google.com/p/selenium/wiki/WebDriverJs

I even try a few things that was documented for Java version like this:

webdriver.Select(driver.findElement(webdriver.By.id("vote"))).selectByValue("5")

And it just simply says that "Select" does not exist.

I went through the source and still cannot find anything that I can use.

like image 709
vpn Avatar asked Apr 07 '13 05:04

vpn


People also ask

How do I select a drop-down?

The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted).

How do I select a dropdown in Selenium using JavaScriptExecutor?

We can use the JavascriptExecutor method to select an option from the dropdown with the help of JavaScriptExecutor. We have to set the dropdown option using the "value" property of the element.


4 Answers

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();
like image 121
nilesh Avatar answered Oct 23 '22 17:10

nilesh


I shared a function to select a drop down item by it's text here.

The code:

function selectOption(selector, item){
    var selectList, desiredOption;

    selectList = this.findElement(selector);
    selectList.click();

    selectList.findElements(protractor.By.tagName('option'))
        .then(function findMatchingOption(options){
            options.some(function(option){
                option.getText().then(function doesOptionMatch(text){
                    if (item === text){
                        desiredOption = option;
                        return true;
                    }
                });
            });
        })
        .then(function clickOption(){
            if (desiredOption){
                desiredOption.click();
            }
        });
}

use with:

driver.selectOption = selectOption.bind(driver);
driver.selectOption(webdriver.By.id('my-dropdown'), 'My Value');
like image 45
Dan Avatar answered Oct 23 '22 17:10

Dan


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
like image 34
Beston Mawarire Avatar answered Oct 23 '22 16:10

Beston Mawarire


I am using webdriverjs and want to select the option by index, so did:

driver.click('#my_select_box').click('#my_select_box option:nth-child(3)')
like image 23
apfrod Avatar answered Oct 23 '22 17:10

apfrod