Methods are provided that you can use to retrieve and set attributes within a SelectOption. For instance, you can set whether or not the option defaults to being selected. You can also set the input value it will use when the form is submitted.
The following example creates three SelectOption objects within a select form. Each SelectOption object below is highlighted. They are named option1, option2 and option3. The option3 object is initially selected.
SelectFormElement list = new SelectFormElement("list1"); SelectOption option1 = list.addOption("Option1", "opt1"); SelectOption option2 = list.addOption("Option2", "opt2", false); SelectOption option3 = new SelectOption("Option3", "opt3", true); list.addOption(option3); System.out.println(list.getTag());
The above code example produces the following HTML tag:
<select name="list1">
<option value="opt1">Option1</option>
<option value="opt2">Option2</option>
<option value="opt3"
selected="selected">Option3</option>
</select>
When you use this tag in an HTML form, it looks like this: