[SalesForce] How to display alert popup based on a value by selecting an account

I have a drop down list which contains all accounts with select an account is also as a value like the following.

enter image description here

I want to display an alert message when I select Select an account only like the following pic shows.

enter image description here

I tried with some of the following code, but the alert popup is coming for each and every value. But i don't want alert popup when i select others.

Vf page:

<script>
    function alertBox() {
        alert("Please select an account");
    }
</script>
<apex:form >
    <apex:pageBlock id="one">
        <apex:selectList size="1" value="{!accid}" id="dropdown_change">
            <apex:selectOptions value="{!records}" />
        </apex:selectList>      
        <apex:commandButton value="Submit" reRender="testPanel" onclick="alertBox()" />
            <apex:param value="{!accid}" assignTo="{!accid}"/>
    </apex:pageBlock>
    <apex:outputPanel id="testPanel">
     {!accid}
    </apex:outputPanel>
</apex:form>
</apex:page>

Apex class:

public class AccountDropdown {

    public string callfunc{get;set;}
    Public String Accid {set;get;}
    List<Selectoption> options = new List<Selectoption>();

    Public List<Selectoption> getrecords() {

        options.add(new Selectoption('Nothing', 'Select a Account'));
        for(Account a : [select id,name from account]) {
            options.add(new Selectoption(a.id, a.name));
        }
        return options;
    }
    public void main(){
        if(accid == 'nothing'){
           callfunc = '<script> alertBox(); </script>';
        }
    }
}

I found some ideas from stack overflow question, But i unable to update this code for vfpage and apex class.

Any ideas?

Best Answer

Try this code:

<apex:page controller="Apex">    
    <apex:form id="form">
        <apex:pageBlock id="one">
            <apex:selectList size="1" value="{!accid}" id="dropdown_change">
                <apex:selectOptions value="{!records}" />
            </apex:selectList>
            <script>
                const selectEl = document.getElementById('{!$Component.form.one.dropdown_change}');
                function alertBox(){
                    if(selectEl.selectedIndex == 0){
                        alert('Select an account');
                    }
                }
            </script>
            <apex:commandButton value="Submit" reRender="testPanel" onclick="alertBox()" />
            <apex:param value="{!accid}" assignTo="{!accid}"/>
        </apex:pageBlock>
        <apex:outputPanel id="testPanel">
            {!accid}
        </apex:outputPanel>
    </apex:form>
</apex:page>
Related Topic