Using Selenium for selecting an option on a select with optgroup

Mugen picture Mugen · Sep 25, 2009 · Viewed 24.9k times · Source

I'm trying to select a value in a select element. I'm using Selenium RC (Java) to run the test cases. I understand that the code for selecting a value is given by:

selenium.select("locator", "value=REQUIRED VALUE")

I'm unable to select the desired value with the above code. I think it might be something to do with optgroup in the select source code. I do not get any exceptions, the command executes fine but looking at the page the required value is not selected. Also, I cant use ids (instead of value) because there arent any. Here is the source code of the selector:

<select>
   <optgroup label="Group1">
      <option value="13">some value1</option>
      <option value="25">some value2</option>
   </optgroup>
   <optgroup label="Group2">
      <option value="18">REQUIRED VALUE</option>
      <option value="34">some value3</option>
      ...
      ...
   </optgroup>
</select>

Is there any way to select the required value using Selenium?

It would be great if we could avoid the option values (such as "18", "34" etc) because these numbers change later as the values change. For example, "REQUIRED VALUE" has a value -18 but if I were to delete this item and add it again its value would be different. Basically this drop-down box is dynamic.

Answer

Dave Hunt picture Dave Hunt · Sep 25, 2009

The value for the required option in your example is actually '18'. Try the following:

selenium.select("locator", "label=REQUIRED VALUE")