1

Can anyone here suggest a method to select an item from a drop down menu, using the item's position in the list?

Say you have a normal drop down menu to select the month of birth.

Example on this page: http://www.plus2net.com/php_tutorial/date-selection.php.

Usually the exported code from the WebDriver IDE will have selected the respective item by name.

Yet I would be more handy to actually select it by list position. Thereby an simple integer ranging 1-12 from a database could be used to select an element on the list. This being more elegant, than selecting from a group of 12 strings (January, February, etc.).

2 Answers 2

3

I don't know what programming language you use, but in Java you can do something like that:

Select select = new Select(driver.findElement(By.id("select")));
select.selectByIndex(1);

Here is the Select class: http://seleniumhq.github.io/selenium/docs/api/java/index.html

0

Using Watir you can select by index as follows:

browser.select_list(:id=> 'month_of_birth').option(:index=> 0).select

In this case we are selecting the first option at the top of the drop down list. Also if you want to count the number of options there are then you can do:

browser.select_list(:id=>'month_of_birth').options.count

You can use name instead of id in both cases if that's what is preferred.

Hope this helps!

2
  • Although this works, the OP seemed to be specifically asking about Selenium and WebDriver. Aug 3, 2014 at 15:37
  • That's fair, I'm just suggesting an alternative. Aug 3, 2014 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.