+ Start a Discussion

Javascript in VisualForce

How do I include a javascript file or put inline script in the page and how do I use that javascript as actions with in a commandButton or commandLink component?
Clint -

There seem to be a fair number of folks that are under the incorrect impression that when you adopt visualforce you throw away everything you know about HTML/javascript etc development and must do everything using components. Nothing could be further from the truth. It is quite common and desireable to use straight DHTML techniques, so by all means go ahead and put script tags in your markup just like you would in any HTML. Use javascript, leverage Dojo/scriptaculous/prototype.js/etc. Use h1's and div's. We are still building for the web after all.

With that said there are many things that VF components can take care of for you that make little sense to do manually via scripting. Web 2.0 functionality like partial updates, invoking server side actions, bidirectional value binding, etc are all things that VF does extremely well and all without you righting a line of code!

Finally, as to using javascript with apex:commandButton/apex:commandLink - these components are specifically designed to invoke action methods in the controller (server side). They do integrate with javascript 100% (e.g. the oncomplete attribute allows you to specify a block of js that will run when an the XHR request completes and the onclick attribute  works like onclick on a  normal  HTML button and allows you to do things like conditionally submit or prompt the user for confirmation).

If what you want is to generate a classic anchor tag we have apex:outputLink (apex:outputButton is strangely absent - something I expect we'll remedy soon) for that express purpose. Another example of a fine grained component that basically maps directly to HTML is apex:image. So why use these? You don't have to but in many cases we will be enhacing the components beyond what the basic HTML element can do - for example in Winter '08 we've added a new richText attribute to <apex:inputTextArea> that allows you to get full bidirectional value binding with a rich text editing UI just by setting richText="true"!

Thank you for your reply. It helped greatly.