[SalesForce] Javascript Alert on change of picklist value

Can someone suggest me a way to display an alert message onchange of picklist values(Different alert message, for different picklist values). Below is the sample code that I'm using, but the javascript isn't working. Any help is much appreciated. Thanks.

VisualForce:

<apex:pageblockSectionItem> <apex:inputfield value="{!picklist1}" onchange="reset();"> </apex:pageblockSectionItem>

    <apex:actionfunction name=reset action="{!check}" rerender="pageBlock">

    <script>
     <apex:outputpanel rendered={!show}>
        var val = {!picklist1}
         if(val == 'yes')
             {
            alert('{!mes}');
                 }
     </apex:outputpanel>
    </script>

Apex Class:

class{
public boolean show{get;set;}
public String mes{get;set;}
public void check(){    
    if(picklist1 == 'yes')
    { 
      show = true;
      mes  = 'you selected yes';
    }

}
}

Best Answer

You can do all that check in Javascript and then call your apex method (if you have to).

Let's assume this is your picklist:

<apex:selectList id="myPicklist" size="1" value="{!selectedValue}" onchange="myPicklistChanged();">
    <apex:selectOptions value="{!myPicklistOptions}" />
</apex:selectList>

And you have your action function (only if you need to call your apex method)

<apex:actionfunction name="reset" action="{!check}" rerender="pageBlock" />

Finally your javascript function that is called from the onchange event on your picklist:

<script>
    function myPicklistChanged()
    {
        var myPicklistElement = document.getElementById('{!$Component.myPicklist}');
        var myPicklistValue = myPicklistElement.options[myPicklistElement.selectedIndex].value;

        if (myPicklistValue == 'value 1')
        {
            alert('value 1');
            // if you don't want to call your apex method
            // return;
        }
        else if (myPicklistValue == 'value 2')
        {
            ...
        }

        // if you still want to call your apex method after this check
        // check();
    }
</script>
Related Topic