function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AnjaanAnjaan 

How to set default value in select list

Hello All

I am using <apex:selectlist  size = "1"> for making a select box. \
i have a number of selectlists and want to show the same data in them but i have to set the different selected values on each list. Here is my Code
Code:
My Controller

public List<SelectOption> getItems() {
                List<SelectOption> options = new List<SelectOption>();
                options.add(new SelectOption('US','US'));
                options.add(new SelectOption('CANADA','Canada'));
                options.add(new SelectOption('MEXICO','Mexico'));
                return options;
        }

public String[] getCountries(){
        return countries;
    }
    public void setCountries(String[] countries){
        this.countries = countries;
    }

 and the page...

Code:
<apex:selectList value="{!countries}" size="1" required="true">
    <apex:selectOptions value="{!items}"/>
 </apex:selectList>

<apex:selectList value="{!countries}" size="1" required="true">
     <apex:selectOptions value="{!items}"/>
</apex:selectList>
                 

 both are showing the same value "USA" i want to show CANADA on the second list by default.......

Please help me


JimRaeJimRae
I don't believe you are setting the default value at all, you are merely showing the first value in the list.  If you want to pre-select a value for the user, you need to add additional code in your getter and setter.

something like this:

Code:
public String[] getCountries(){
        if(countries==null){countries='CANADA'}
        return countries;
    }

 Another technique you could use (I do) is to create a "dummy" entry at the top that forces the user to select something.
For the first option add code, do something like this:
 options.add(new SelectOption('','--SELECT COUNTRY--'));
then you can test to make sure that some value was selected.