Javascript examples with Apex

Example1: Sum Calculation using JavaScript Function

Visualforce page:

<apex:page sidebar=”false” id=”p1″>
<script>
function sum(){
alert(‘hello’);
var a=parseInt(document.getElementById(‘p1:f1:n1’).value);
alert(a);
var b=parseInt(document.getElementById(‘p1:f1:n2’).value);
alert(b);
alert(‘Total value is ‘+(a+b));
}
</script>
<apex:form id=”f1″>
N1: <apex:inputtext id=”n1″/><br/>
N2: <apex:inputtext id=”n2″/><br/>
<apex:commandButton value=”Sum” onclick=”sum()”/>
</apex:form>
</apex:page>

Example2: CheckBox Hide Or Unhide the components based on Checked Property:
Visualforce page:
<apex:page sidebar=”false” id=”p1″>
<script>
function HUcomponent(){
var chkResult = document.getElementById(‘p1:f1:chk1’).checked;
alert(chkResult);
if(chkResult){
document.getElementById(‘p1:f1:out’).style.display=”block”;
}
else
{
document.getElementById(‘p1:f1:out’).style.display=”none”;
}
}
</script>
<apex:form id=”f1″>
<apex:inputcheckbox id=”chk1″ onclick=”HUcomponent()”/> <br/>
<apex:outputpanel id=”out” style=”display:none;”>
name: <apex:inputtext /> <br/>
City: <apex:inputtext /><br/>
<apex:commandButton value=”Save”/>
</apex:outputpanel>
</apex:form>
</apex:page>