If you ever come across the need to select an option in a drop down list when you only have some of the text here is how you can select a particular option oin a drop down list using a partial text selector. In this example the drop down list would be populated with strings formatted as follows: FirstName LastName – Address. eg “John Smith – 1001 Main St”. For the test we only have the person’s name available to us.


IWebElement ddlList = driver.FindElement(By.Id("ddlList"));
string strName = "John Smith";

ddlList.FindElement(By.XPath(string.Format("./option[starts-with(text(), '{0}')]", strName))).Click();

This example uses C# language to illustrate the point, I will provide a Java version at a later stage.
To use drop down selects in WebDriver you have to define the SELECT object as well as the OPTION object. This may be due to the way these are coded in HTML (This example is taken from http://www.w3schools.com/tags/tag_select.asp with an added Id attribute in the <SELECT> tag ):
<select id=”cartypes”>
<option value=”volvo”>Volvo</option>
<option value=”saab”>Saab</option>
<option value=”mercedes”>Mercedes</option>
<option value=”audi”>Audi</option>
So in WebDriver we have to define the SELECT element first, and then using this object we define the OPTION object. Once we have out option item defined we can select it by using the displayed text, its index or its value. There are separate methods for each of these; SelectByText(), SelectByIndex() and SelectByValue() respectively. Each of the the SelectBy examples below are selecting the same item “Mercedes” in the car types drop down list:
//SELECT element defined
var ddlCarTypes = driver.FindElement(By.Id(“cartypes”));

// OPTION element defined in the car types drop down list
var selectOption = new SelectElement(ddlCarTypes);

// Select the same item in the list using Text, Index or Value: