using javascript in visualforce page

You can customise functionality in your visualforce page using java script. You can pass parameters to the java script, show pop ups, confirm messages.Visualforce page validation messages can be shown as pop ups, you can also call controller methods from java script.

Lets not discuss on what more we can do with java script, instead just write our very first very simple visualforce page that uses java script in it. Let us take a scenario where we can use java script in vf page and work on it.

Let us define our problem first:
Show a validation pop up message when i click on a button, it should show message if the input field on the page does not have any value in it.
If you have typed a value in the text box then just show the input value in the pop up.

Solution for the above scenario:

                      Visualforce page

<!-- Using java script in visualforce page -->
<apex:page controller="DynamicVisualforceController">
  <apex:form >
        <apex:pageBlock >
           Input Here  : <apex:inputText id="inptID"/>
                       <apex:commandButton onclick="MyjavaFunction('{!$Component.inptID}')" value=" Submit "/>
  <!-- Java script starts Here -->
   function MyjavaFunction(ReceiveInputID){
    var inputValue = document.getElementById(ReceiveInputID).value;
         if(inputValue == ''){
            alert('You did not eneter any value in input box');
            alert(' You entered :: '+inputValue);

  • Java script should be written between the tags <script> and </script>
In this example we are calling the java script function "MyjavaFunction" once we click on the command button "Submit".     <apex:commandButton onclick="MyjavaFunction('{!$Component.inptID}')" value=" Submit "/>

As you can see, we are passing some parameter while calling this function. This parameter "{!$Component.inptID}" is the id of inputtext component.This will be useful in java script function to get the value that we input in the textbox.
Following statement in Java script gets you the value that you input in the text box:       var inputValue = document.getElementById(ReceiveInputID).value;
Once we get the input value just check if it is blank and give message using "alert" statement in java script else show the input value.


  1. i have written java script for valdiation in visualforce page it is working fine but when i am using same page in public websites the java script is not invoking

  2. Hi Yoganand,

    thanks for the code above, it is helpful for a beginner. If I want to pass inputValue into standard extension controller to access it there, how do I do that?

  3. tq ..helpful for beginners