How to display the selected value from apex:selectOptions in Salesforce Visualforce page?

How to display the selected value from apex:selectOptions in Salesforce Visualforce page?

Sample Code:

Visualforce Page:

<apex:page controller="SampleVFPageController">
    <apex:form>
        <apex:actionFunction name="onAccountChange" action="{!fetchAccount}" reRender="selAccName"/>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:selectList value='{!selectedAccount}' label="Select an Accont" onchange="onAccountChange()">
                    <apex:selectOptions value="{!listOptions}" />
                </apex:selectList>
            </apex:pageBlockSection>
            <apex:pageBlockSection>
                <apex:outputPanel id="selAccName">
                    Selected Account name is {!selectedAccountName}
                </apex:outputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public class SampleVFPageController {

    public List < SelectOption > listOptions { get; set; }
    public String selectedAccount { get; set; }
    public String selectedAccountName { get; set; }
    
    public SampleVFPageController() {
    
        listOptions = new List < SelectOption >();
        
        for ( Account objAcc : [ SELECT Name FROM Account LIMIT 10 ] ) {
            
            SelectOption objSO = new SelectOption( objAcc.Name, objAcc.Name );
            listOptions.add( objSO );
            
        }
    
    }
    
    public void fetchAccount() {
    
        selectedAccountName = selectedAccount;
    
    }

}

Output:

Leave a Reply