[SalesForce] execute javascript function whenever the condition in onclick attribute is true

So I don't want to add another code in my controller class.

Is there a way I can accomplish this?

I have an actionFunction named makeEditable

<apex:actionFunction name="makeEditable" action="{!dispEdit}" reRender="pbt" />

I have an outputpanel with onclick attribute

<apex:outputPanel  
onclick="{!
IF(canEdit, 
'makeEditable(\'{!fdsw.fds.Forecast_User__c}|{!fdsw.fds.User_Role__c}|commit\')',
'alert(/'Unable to edit this field/')')
}" > 
--someFields--- 
</apex:outputPanel>

the onclick is not working. Am I doing it wrong?

Please help me.

Thanks

Best Answer

When trying to generate JavaScript in Visualforce, you can check the results by using your browser's "Inspect Element" feature and should look at your browser's JavaScript console too for errors. (See e.g. How do I start to debug my own Visualforce/JavaScript?)

Your Visualforce is emitting:

onclick="makeEditable(\'#{fdsw.fds.Forecast_User__c}|{!fdsw.fds.User_Role__c}|commit\')"

rather than some valid JavaScript (assuming commit is a JavaScript variable) such as e.g.:

onclick="makeEditable(true || true || commit)"

You need something like this:

<script>
function unableToEditAlert() {
    alert('Unable to edit this field');
}
</script>
<apex:outputPanel  
onclick="{!
IF(
canEdit,
'makeEditable(' + IF(ISBLANK(fdsw.fds.Forecast_User__c), 'false', 'true') + ' || ' + IF(ISBLANK(fdsw.fds.User_Role__c), 'false', 'true') + ' || commit)',
'unableToEditAlert()'
)}"
> 
--someFields--- 
</apex:outputPanel>

The alert is awkward because there doesn't seem to be a way (in this context) to escape the quotes in Visualforce in a way that results in valid JavaScript in the generated HTML. Hence the additional function.