[SalesForce] Adding/defaulting a null value to a selectlist on a Visualforce page

I am creating a VF page that basically has different "pages" that each have different questions on them. Each "page" is a different outputpanel that is rendered depending on clicking a Continue or Back button. I have created a few picklists using selectList/selectOption to make other questions appear or not. The problem I'm running into is that I want to make these picklists required before being able to move to the next page, but I can't seem to do so because there is no null option. I would like the picklist to start as null which would make the user choose one of the options before they can continue.

For example, with the following code snippet, I can create a picklist on the page with all the options, but the user can just move to the next page without making a choice.

Class:

public List < SelectOption > getisNDA() {
        List < SelectOption > options3 = new List < SelectOption > ();
        List < String > tempList = new List < String > ();            
        tempList.add('Yes');
        tempList.add('No');
        for (String s: tempList)
            options3.add(new SelectOption(s, s));
        return options3;
    }

Page:

<apex:selectList id="sel3" value="{!NDA2}" multiselect="false" size="1" tabIndex="70" styleclass="inputc" required="true">
                                <apex:actionSupport event="onchange" action="{!NDAupdate}" rerender="NDAQ1, NDAQ2" />
                                <apex:selectOptions value="{!isNDA}" />
                            </apex:selectList>

Best Answer

I usually just do this.

Class:

public List <SelectOption> getisNDA() {
    List<SelectOption> options3 = new List<SelectOption>{
        new SelectOption('','-Select-')
    };
    List <String> tempList = new List <String> ();            
    tempList.add('Yes');
    tempList.add('No');
    for (String s: tempList)
        options3.add(new SelectOption(s, s));
    return options3;
}

And then in a the page I add a style class in the page to set the first option (-Select-) color to grey.

select.select-options option:first-child, {
    color: #ccc;
}

<apex:selectList id="sel3" value="{!NDA2}" multiselect="false" size="1" tabIndex="70" styleclass="inputc" required="true" styleClass="select-options">
    <apex:actionSupport event="onchange" action="{!NDAupdate}" rerender="NDAQ1, NDAQ2" />
    <apex:selectOptions value="{!isNDA}" />
</apex:selectList>

Additionally, you can add in some JavaScript to disable the first option (-Select-) as well.

document.querySelectorAll('.select-options option:first-child').forEach(function(e) { e.disabled = true; });
Related Topic