In my Delphi application I’m using a TWebBrowser control, where I have loaded an HTML document, containing a <select> element (drop down list) with a few <option> items (drop down list items). Let’s say, I have the following HTML document loaded in my web browser:
<html>
<body>
<select id="ComboBox">
<option value="firstvalue">First Value</option>
<option value="secondvalue">Second Value</option>
<option value="thirdvalue">Third Value</option>
</select>
</body>
</html>
How can I programatically select e.g. the <option>, whose value attribute is thirdvalue ? Or in other words, how can I programatically select the third item in this drop down list, when I know only that this item’s value attribute is thirdvalue ?
You can use the
IHTMLSelectElementinterface with itsselectedIndexproperty for instance. As a showcase I’ve made the following function.SelectOptionByValue function
The following function tries to find, and select (if found) an
<option>(a drop down list item) of a givenvalueattribute value in a specified<select>element (drop down list). If no<option>is found, the current drop down list selection is cleared (no item is selected).Parameters:
<select>element (element ID of a drop down list)<option>element value (value of a drop down list item)Return value:
If the
<option>with a givenvalueis successfully found (and selected), the return value is the index of that option in a specified drop down list, -1 otherwise.Source code:
Example usage:
To select the item with
thirdvaluevalue in drop down list from the HTML document from the question it’s possible to use this code (assuming in theWebBrowser1component here is loaded that document):Example HTML document from the question: