+ Start a Discussion
Rick MacGuiganRick MacGuigan 

Using javascript and $Component

I can't seem to get a handle on a input field from my javascript function 'checkNumbers.' The initial alert pops up with the onChange event. The second alert pops up but with no value. The field is a percent type so the String() function is used. However, I think the issue is with traversing the objects using $Component. Below is my VF code. Am I traversing this object correctly ?
<apex:page id="page" standardController="Comm_Auto_Audit_Sample_Policy__c"  extensions="AuditCommAutoPolicySampleController"  > 
<script type="text/javascript">
function closepage()
    {
top.window.close();
}
 
</script>

<script>
function checkNumbers() {
alert('Debug 1');
var x = document.getElementById("{!$Component.page.form1.block1.ajaxrequest2.section2.value2}").innerHTML;  
alert(String(x));
}
</script>

<!-- ********************************************** -->

<!--Establish control variables 
The control variables are used to streamline naming conventions and ease rendering references. 
//-->

<!--Set Object reference variable -->
<!-- declare variable for dependency to field in new controller. -->
<apex:variable var="AuditID" value="{!Comm_Auto_Audit_Sample_Policy__c.Audit__c}" />
<apex:variable var="sample" value="{!Comm_Auto_Audit_Sample_Policy__c}" />

<!--Contoller Information variables --> 
<apex:variable var="a" value="{!Audit}" /> 


<!-- ********************************************** -->
<apex:form id="form1">
<apex:pageBlock id="block1" title="Commercial Auto Audit Sample Data (Policy: {!Comm_Auto_Audit_Sample_Policy__c.Policy_Number__c})" >   
<!-- ********************************************** -->

<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!Save}"/> 
<apex:commandButton value="Save and Return to Template" action="{!saveAndReturn}"/> 
</apex:pageBlockButtons>
 
<!--Debug info for state changes set rendered="true" to enable section -->
<apex:pageBlockSection columns="1" id="testsection1" title="TEST & Debug Section" rendered="false" >
<!--
        ....Parent ID Number is : "{!ParentID}"<br></br>
        ....Personal Auto Product is : "{!PersonalAutoProduct}"<br></br>     
        ....Personal Parent Audit Name is : "{!AuditName}"<br></br> 
//-->
</apex:pageBlockSection>
<script>twistSection(document.getElementById("{!$Component.testsection1}").childNodes[0].childNodes[0]); </script> 
 

<!-- ************************************************************************************************ -->

<apex:outputPanel id="ajaxrequest2">
<apex:pageBlockSection columns="1" id="section2" title="Operations" rendered="{!Operations}" >

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c}" id="operation" rendered="{!TypeOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>  

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c}" rendered="{!RadiusOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Local__c}" style="color:blue;" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Local') && (RadiusOfOperations)}"  />

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Intermediate__c}"  style="color:blue;" id="value2" onchange="checkNumbers();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Intermediate') && (RadiusOfOperations)}"  />

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Long_Haul__c}"  style="color:blue;" id="value1" onchange="checkNumbers();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Long-Haul') && (RadiusOfOperations)}"  >
    <apex:actionSupport event="onchange" reRender="longhaul" />
    </apex:inputField>

</apex:pageBlockSection>
</apex:outputPanel>

</apex:pageBlock>
</apex:form>
</apex:page>

 
Best Answer chosen by Rick MacGuigan
SarfarajSarfaraj
Rick, The following code works for me. Check if this meets your requirement,
function checkNumbersOps() {
    var val1 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value1}") != null)
		val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
	if(isNaN(val1))
		val1 = 0;
	var val2 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value2}") != null)
		val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
	if(isNaN(val2))
		val2 = 0;
	var tot = val1 + val2;
    if (tot < 100 || tot > 100)  
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations not equal to 100.';
    }
	else
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations equal to 100.'; 
    }
}

 

All Answers

SarfarajSarfaraj
Please use this,
var x = document.getElementById("{!$Component.page.form1.block1.section2.value2}").value;
instead of,
var x = document.getElementById("{!$Component.page.form1.block1.ajaxrequest2.section2.value2}").innerHTML;
--Akram
Rick MacGuiganRick MacGuigan
Akram - thanks for the response. Works perfectly ! I'm adding this value to produce a total. What I would like to do is display output text on the page is the total = 100 and a differnt text if the total < 100. Any suggestions on how to do that on the VF page ?
SarfarajSarfaraj
Which fields are you adding?
Rick MacGuiganRick MacGuigan
Akram - here is what I am trying to do to generate an out text value .
 
<script>
function checkNumbers() {

var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
var val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
var tot = val1 + val2;
alert(String(tot)+'%');  //debug only

//next I test the total then write that to the output text.

var thresholdText = document.getElementById("{!$Component.page.form1.block1.section2.answer}").value);    
    if (tot < 100) {
    value.thresholdText.value = " Percent Radius of operations not equal to 100." 
    } else {
    value.thresholdText.value = " Percent Radius of operations equal to 100."  
    }  
    }
</script>


On the Visualforce page I would like to simply display one of the two strings into 'value' for id=answer rather than use validation which forces a round trip to the server. 

<apex:outputText id="answer" value="">
  </apex:outputText>

 
Rick MacGuiganRick MacGuigan
Akram, I got this to work but not sure if this is the best approach. Would appreciate your thoghts. Do we need to use the innerHTML attribute ?
 
<script>
function checkNumbers() {

var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
var val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
var tot = val1 + val2;
alert(String(tot)+'%');


    if (tot < 100) {
    document.getElementById('{!$Component.page.form1.block1.section2.answer}').innerHTML = 'Percent Radius of operations not equal to 100.';

    } else {
    document.getElementById('{!$Component.page.form1.block1.section2.answer}').innerHTML = 'Percent Radius of operations equal to 100.'; 
    }  
    }

</script>


On the Visualforce page I would like to simply display one of the two strings into 'value' for id=answer rather than use validation which forces a round trip to the server. 

<apex:outputText id="answer" value="">
  </apex:outputText>

 
SarfarajSarfaraj
Rick, If you want to avoid server side interaction for this event, this is the best approach to do this. Just a note on the coding syntax, till now you have used plain old javascript. Which will work perfectly. However you may use jquery as well, if you want. It will give you some shorthand and the code lines will be smaller. For example, Instead of var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value); You may use, var val1 = parseInt($("[id$='value1']").val()); Instead of document.getElementById('{!$Component.page.form1.block1.section2.answer}').innerHTML = 'Percent Radius of operations not equal to 100.'; You may write, $([id$='answer']}').html("Percent Radius of operations not equal to 100."; I have assumed all Id attributes in your page are unique. To use jquery you have to include the plugin to your page, --Akram
Rick MacGuiganRick MacGuigan
Akram, thanks for this. I appreciate your reposes. I have used jquery on prior projects. However, I did not have to add the plugin however. The sample below I just used <style> in the VF page. Dov you see jquery replacing javascript ? 

You may find this useful:
 
<!-- JQuery attribute that turns off the As Of subtitle on the analytics:reportChart components -->
<style>
.asOfDate{display:none;}
</style>

 
Rick MacGuiganRick MacGuigan
Akram, if either of the inputFields on my VF page are not rendered how is that represented to javascript ?  Can I simply test it as if(val1 == '') ? In some cases val1 or val2 may not be rendered on the page and I just need to make sure the one that is rendered is = 100%.
SarfarajSarfaraj
Depends on how you are controlling the render mechanism. If you are using css (display: none) to hide the element, then you need to check the visibility of the element to decide. The element will be present in the DOM. For example,
if(document.getElementById("idOfElement").style.display == "none")
    --do something--
If you are using rendered attribute of salesforce, the element will not be present in the DOM. In that case you have to check if the element is present. Any operation to determine value or style of the element will give you NPE. For example,
if(document.getElementById("idOfElement") == null)
    --do something--
Rick MacGuiganRick MacGuigan
Akram, thanks. I am using rendering to hide the fields. However, not getting either of the lines below to detect null. rather it shows the value NaN.
 
if (document.getElementById("value1") == null;

or

if (document.getElementById("{!$Component.page.form1.block1.section2.value1}").value) == null;

or

var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);   
      if(val1 == null){
      var val1 = 0;
      //alert(String('val1 null' + val1));
      } else {
      //alert(String('val1 ' + val1));  //this prints out NaN
      //do nothing
      }

 
SarfarajSarfaraj
Can you please post the code for the vf page showing the input field.
Rick MacGuiganRick MacGuigan
Here is the VF code: 
 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c}" rendered="{!RadiusOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Local__c}" style="color:blue;" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Local') && (RadiusOfOperations)}"  />
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Intermediate__c}"  style="color:blue;" id="value2" onchange="checkNumbersOps();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Intermediate') && (RadiusOfOperations)}"  /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Long_Haul__c}"  style="color:blue;" id="value1" onchange="checkNumbersOps();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Long-Haul') && (RadiusOfOperations)}"  /> 

<apex:outputText id="answerOperation" value="" style="color:blue"  >
  </apex:outputText>

 
Rick MacGuiganRick MacGuigan
Akram, even with both the value1 and value2 fields rendered the alert(String('val1 is Null ' + val1)) shows whether I clear the value or enter a value in this field.  Almost like it is not reading the value in the field. 
if (document.getElementById("value1") == null){
alert(String('val1 is Null ' + val1));
} else {
alert(String('val1 is Not Null ' + val1));
}

 
SarfarajSarfaraj
Rick, Seems strange to me. Can you please share the entire page and controller code? I will try this in my org. 
Rick MacGuiganRick MacGuigan
Akram, sure . Below is the VF page and related controller. I had to shorten some insignificant VF sections to reduce the text limitations.

 
<apex:page id="page" standardController="Comm_Auto_Audit_Sample_Policy__c"  extensions="AuditCommAutoPolicySampleController"  > 

<!--Notes 
This page is used when instantiating a NEW sample. An Apex extended controller is required. The parent ID is passed via URL parms in buttons on related list or embedded visual
force page on Audit object. 
This script must be outside of pageBlockSections to keep section from auto collapsing after page is rerendered. 
<script>twistSection(document.getElementById("{!$Component.testsection1}").childNodes[0].childNodes[0]); </script>

//-->

<!-- CSS styles used for decorating the pageblock sections -->
  <style>
            body .bPageBlock .pbBody .red .pbSubheader{
                background-color:lightblue;
            }
            body .bPageBlock .pbBody .red .pbSubheader h3{
                color:black;
            }
            body .bPageBlock .pbBody .grey .pbSubheader{
                background-color:lightblue;
            }
            body .bPageBlock .pbBody .grey .pbSubheader h3{
                color:black;
            }
   </style>  
<script type="text/javascript">
function closepage()
    {
top.window.close();
}
 
</script>

<script type="text/javascript">

function checkNumbersOps() {
//alert('Debug 1');

//if (document.getElementById("value1") == null){
//alert(String('val1 is Null ' + val1));
//} else {
//alert(String('val1 is Not Null ' + val1));
//}



      
    var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
    
/*       
      if(val1.value != null){
      //do nothing      
      alert(String('val1 ' + val1));
      } else {
      var val1 = 0;
      alert(String('val1 NULL' + val1));     
      }
*/   
    
    
/*       
      if(val1 == null){
      var val1 = 0;
      //alert(String('val1 null' + val1));
      } else {
      //alert(String('val1 ' + val1));
      //do nothing
      }
*/
      
    var val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
/*    
      if(val2 == null){
      var val2 = 0;
      //alert(String('val2 null' + val2));
      } else {
      //alert(String('val2 ' + val2));
      //do nothing
      }      
*/


      
var tot = val1 + val2;
//alert(String(tot)+'%');
var thresholdText = (document.getElementById("{!$Component.page.form1.block1.section2.answerOperation}").value); 

    if (tot < 100 || tot > 100)  {
    document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations not equal to 100.';
    } else {
    document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations equal to 100.'; 
    }    
    }

function checkNumbersEnviron() {
//alert('Debug 1'); 
var val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value3}").value);
var val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value4}").value);
var tot = val1 + val2;
//alert(String(tot)+'%');
var thresholdText = (document.getElementById("{!$Component.page.form1.block1.section2.answerEnviron}").value); 

    if (tot < 100 || tot > 100) {
    document.getElementById('{!$Component.page.form1.block1.section2.answerEnviron}').innerHTML = 'Total percent operating environment not equal to 100.';
    } else {
    document.getElementById('{!$Component.page.form1.block1.section2.answerEnviron}').innerHTML = 'Total percent operating environment equal to 100.'; 
    }    
    }    
    
</script>


<!-- ********************************************** -->

<!--Establish control variables 
The control variables are used to streamline naming conventions and ease rendering references. 
//-->

<!--Set Object reference variable -->
<!-- declare variable for dependency to field in new controller. -->
<apex:variable var="AuditID" value="{!Comm_Auto_Audit_Sample_Policy__c.Audit__c}" />

<apex:variable var="sample" value="{!Comm_Auto_Audit_Sample_Policy__c}" />

<!--Contoller Information variables --> 
<apex:variable var="a" value="{!Audit}" /> 

<!--General Information variables --> 
<apex:variable var="PersonalAutoProduct" value="{!a.Personal_Auto_Product__c}" /> 
<apex:variable var="ParentID" value="{!a.Id}" />
<apex:variable var="AuditName" value="{!a.Name}" />

<!--Policy Information control variables --> 
<apex:variable var="PolicyInformation" value="{!a.Policy_Information__c}" /> 
<apex:variable var="MGAName" value="{!a.MGA_Name__c}" />
<apex:variable var="InsuredName" value="{!a.Insured_Name__c}" />
<apex:variable var="EffectiveDate" value="{!a.Effective_Date__c}" />
<apex:variable var="PriorCarrier" value="{!a.Prior_Carrier__c}" />
<apex:variable var="ExpiringPremium" value="{!a.Expiring_Premium__c}" />
<apex:variable var="PolicyTerm" value="{!a.Policy_Term__c}" />
<apex:variable var="InsuredPrimaryLocation" value="{!a.Insureds_Primary_Location__c}" />
<apex:variable var="OtherGaragingLocation" value="{!a.Other_Garaging_Locations__c}" />
<apex:variable var="AgentCommission" value="{!a.Agent_Commission__c}" />
<apex:variable var="AgentName" value="{!a.Agent_Name__c}" />
<apex:variable var="MCS90Endorsement" value="{!a.MCS_90_Endorsement__c}" />
<apex:variable var="SignedUMUIMRejection" value="{!a.Signed_UM_UIM_Rejection__c}" />
<apex:variable var="OtherLinesOfBusinessWritten" value="{!a.Other_Lines_of_Business_Written__c}" />
<apex:variable var="SIR" value="{!a.SIR__c}" />
<apex:variable var="ThirtyDayPolicyIssuance" value="{!a.Thirty_Day_Policy_Issuance__c}" />
<apex:variable var="SymbolsAppropriate" value="{!a.Symbols_Appropriate__c}" />


<!--Limit Information control variables --> 
<apex:variable var="LimitsDeductiblesPremium" value="{!a.Limits_Deductibles_Premium__c}" /> 
<apex:variable var="LiabilityLimits" value="{!a.Liability_Limits__c}" /> 
<apex:variable var="UMLimits" value="{!a.UM_Limits__c}" /> 
<apex:variable var="UIMLimits" value="{!a.UIM_Limits__c}" /> 
<apex:variable var="UMUIMLimits" value="{!a.UM_UIM_Limits__c}" /> 
<apex:variable var="PIPLimits" value="{!a.PIP_Limits__c}" /> 
<apex:variable var="Comprehensive" value="{!a.Comprehensive__c}" /> 
<apex:variable var="Collision" value="{!a.Collision__c}" /> 


<!--Operations Information control variables -->
<apex:variable var="Operations" value="{!a.Operations__c}" /> 
<apex:variable var="TypeOfOperations" value="{!a.Type_of_Operations__c}" /> 
<apex:variable var="TypeOfGoodsHauled" value="{!a.Type_of_Goods_Hauled__c}" /> 
<apex:variable var="TypeOfService" value="{!a.Type_of_Service__c}" /> 
<apex:variable var="RadiusOfOperations" value="{!a.Radius_of_Operations__c}" /> 
<apex:variable var="OperatingEnvironment" value="{!a.Operating_Environment__c}" /> 
<apex:variable var="UnitCountByVehicleType" value="{!a.Unit_Count_by_Vehicle_Type__c}" /> 

<!-- ********************************************** -->
<apex:form id="form1">
<apex:pageBlock id="block1" title="Commercial Auto Audit Sample Data (Policy: {!Comm_Auto_Audit_Sample_Policy__c.Policy_Number__c})" >   
<!-- ********************************************** -->

<apex:outputPanel layout="none"  >
<b>Audit Ref:</b> &nbsp; <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.Audit__c}"  /> 
</apex:outputPanel>   

<!-- <apex:outputPanel layout="none" rendered="{!IsNew=false}" > -->
<apex:outputPanel layout="none" > 
<!-- use outputText component to format date returned as data only   --> 
<p>
<b>Audit Ref:</b> &nbsp; <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.Audit__c}"  /> &nbsp; <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.Audit__r.Cedent_Account_CCA_PS__c}"/>   
<br><b>Sample No.</b> &nbsp;  <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.Name}"/> &nbsp;  <b>Policy:</b>  &nbsp; <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.Policy_Number__c}"/> &nbsp; Created ( 
 <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
  <apex:param value="{!Comm_Auto_Audit_Sample_Policy__c.CreatedDate}" /> 
 </apex:outputText> 
)  by: <b> <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.CreatedById}"/> </b>  &nbsp; <b> Last Modified By: </b>  <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.LastModifiedById}"/>  on &nbsp; <apex:outputField value="{!Comm_Auto_Audit_Sample_Policy__c.LastModifiedDate}"/> </br> </p>
  </apex:outputPanel> 
  

<p><b>Hello {!$User.FirstName}!  &nbsp;&nbsp;&nbsp;  <font color='blue'>   Enter audit information for this sample below. </font></b></p> 

<!-- enable display of messages for all conditions -->
<apex:messages title="data incorrectly entered." style="background-color:yellow; color: red" /> 
 
<apex:pageBlockButtons location="top">
<!--  <apex:commandButton onclick="checkNumbers()" value="Click"/> -->

<apex:commandButton value="Save" action="{!Save}"/> 
<apex:commandButton value="Save and Return to Template" action="{!saveAndReturn}"/> 
<apex:commandButton value="Audit Template Screen" immediate="true" action="{!ReturnMe}"/>  
<!-- call script to close the visualforce tab, else the tab stays open Deprecated since we no longer open the sample in a new window--> 
<!-- <apex:commandButton value="Audit Template Screen" onclick="closepage();"  /> -->
 
</apex:pageBlockButtons>  
 
 
 
<!--Debug info for state changes set rendered="true" to enable section -->
<!-- Control state information - DO NOT DELETE THIS  set rendered="true" to display this section -->
<apex:pageBlockSection columns="1" id="testsection1" title="TEST & Debug Section" rendered="false" >
<!--
        ....Parent ID Number is : "{!ParentID}"<br></br>
        ....Personal Auto Product is : "{!PersonalAutoProduct}"<br></br>     
        ....Personal Parent Audit Name is : "{!AuditName}"<br></br> 
//-->
</apex:pageBlockSection>
<script>twistSection(document.getElementById("{!$Component.testsection1}").childNodes[0].childNodes[0]); </script> 
 
 <!-- ************************************************************************************************ -->

 <!-- ************************************************************************************************ -->

<apex:outputPanel id="ajaxrequest2">

<!-- OPERATIONS  -->

<!-- <apex:pageBlockSection columns="1" id="section2" title="Operations" rendered="{!RatingInformation=true}"> -->
<apex:pageBlockSection columns="1" id="section2" title="Operations" rendered="{!Operations}" >


<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c}" id="operation" rendered="{!TypeOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>  

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Goods_Hauled__c}" rendered="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c='Commercial' && TypeOfGoodsHauled}" >

    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>  
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Other_Goods_Hauled__c}"  style="color:blue;" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Type_of_Goods_Hauled__c,'Other') && (TypeOfGoodsHauled)}"  />
 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Service__c}" rendered="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c='Livery' && TypeOfService}" >
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>   
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Other_Service_Type__c}" rendered="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Service__c='Other'}" />  

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c}" rendered="{!RadiusOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="section2" />
    </apex:inputField>
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Local__c}" style="color:blue;" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Local') && (RadiusOfOperations)}"  />
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Intermediate__c}"  style="color:blue;" id="value2" onchange="checkNumbersOps();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Intermediate') && (RadiusOfOperations)}"  /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Long_Haul__c}"  style="color:blue;" id="value1" onchange="checkNumbersOps();" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Long-Haul') && (RadiusOfOperations)}"  /> 
<!--<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Percent_Intermediate__c}"  style="color:blue;" id="value2" onchange="foo(this);" rendered="{!CONTAINS(Comm_Auto_Audit_Sample_Policy__c.Radius_of_Operations__c,'Intermediate') && (RadiusOfOperations)}"  /> -->

<!--   <apex:actionSupport event="onchange" reRender="longhaul" /> -->
<!--    </apex:inputField>  --> 

<apex:outputText id="answerOperation" value="" style="color:blue"  >
  </apex:outputText>

<!-- <apex:outputText value="{!o.Amount}" style="color:{!IF(value='', 'red', 'blue')};"/> -->

<!--........................................... -->

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Operating_Environment_Rural__c}" style="color:blue;" id="value3" onchange="checkNumbersEnviron();" rendered="{!OperatingEnvironment}" /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Operating_Environment_Urban__c}" style="color:blue;" id="value4" onchange="checkNumbersEnviron();" rendered="{!OperatingEnvironment}" /> 
<apex:outputText id="answerEnviron" value="" style="color:blue"  >
  </apex:outputText>

<HR></HR>

<b>&nbsp;&nbsp;&nbsp;<font color='blue'>Type of Vehicles</font></b>

<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Private_Passenger__c}" rendered="{!UnitCountByVehicleType}" />
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Light__c}" rendered="{!UnitCountByVehicleType}" /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Medium__c}" rendered="{!UnitCountByVehicleType}" /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Heavy__c}" rendered="{!UnitCountByVehicleType}" /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Tractor__c}" rendered="{!UnitCountByVehicleType}" /> 
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Trailers__c}" rendered="{!UnitCountByVehicleType}" />  
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.TOTAL_Number_of_Vehicles__c}" rendered="{!UnitCountByVehicleType}" />



</apex:pageBlockSection>

<!-- script used to collapse sections initially. Otherwise they do not trigger event -->
<!-- Keep section expanded when creating new page, else collapse the section -->
<!--<apex:outputPanel layout="none" rendered="{!IF(isNew,false,true)}"> -->
<apex:outputPanel layout="none" >
<script>twistSection(document.getElementById("{!$Component.section2}").childNodes[0].childNodes[0]); </script> 
</apex:outputPanel>
</apex:outputPanel>

 <!-- ************************************************************************************************ -->
 
 <!-- ************************************************************************************************ -->

 <!-- ************************************************************************************************ -->

</apex:pageBlock>
</apex:form>


<!-- RELATED LIST EXPOSED HERE  -->
<!-- placing related list at end of main objects fields allows the use of the save standard controller for the whole page. Reduces need for apex extended function. -->
<apex:pageBlock title="Add Significant Loss Detail below." mode="detail">


<!-- <apex:outputPanel layout="none" rendered="{!IsNew}" > -->
<apex:outputPanel layout="none"  >
<font color='blue'>Save the audit sample to start adding losses.</font>
</apex:outputPanel>


<apex:outputPanel id="ajaxrequest4" styleClass="blue" layout="block">
<apex:pageBlockSection columns="1" id="section5" title="Add Significant Loss Detail" >

<apex:relatedList list="Significant_Losses__r"  /> 

</apex:pageBlockSection>
<!-- script used to collapse sections initially. Otherwise they do not trigger event -->
<!-- Keep section expanded when creating new page, else collapse the section -->
<!-- <apex:outputPanel layout="none" rendered="{!IF(isNew,true,false)}"> -->
 <script>twistSection(document.getElementById("{!$Component.section5}").childNodes[0].childNodes[0]); </script>
<!-- </apex:outputPanel>  -->
 
</apex:outputPanel> 
</apex:pageBlock>
</apex:page>

Here is the controller;
 
public with sharing class AuditCommAutoPolicySampleController {

/*
This code supports the PROD_V2_Audit_Auto_PolicySample visualforce page.
FUNCTION:
New record Receives parent ID (accID) passed via commandbutton or custom button on parent related list.
AccId must be passed via URL since we are instantiating a new object reccord which is not saved.
accID is needed to query parent fields that are used on the visualforce page for rendering.
A list object is used for the SOQL query to the parent.  
The parent ID is loaded into the related list field on the instantiated object to establish relationship when saved. 
Note: 
//ApexPages.addMessages (plural) accepts only an exception. ApexPages.addMessage (singular) accepts a Message object 
*/
    //Protected Members
    private final ApexPages.StandardController stdController;  // corrected spelling of stdContoller
    private final string auditIdPrefix;

    //Properties
    public boolean IsNew {get;set;}

    public Comm_Auto_Audit_Sample_Policy__c AuditCommercialAutoPolicySample {get;set;}
    public Audit__c Audit {get;set;}

    //Constructors
    public AuditCommAutoPolicySampleController(ApexPages.StandardController controller) {
        try {
            stdController = controller;
            
            //Init Properties
            this.AuditCommercialAutoPolicySample =  (Comm_Auto_Audit_Sample_Policy__c)controller.getRecord();  
            this.Audit = new Audit__c();
            this.IsNew = (this.AuditCommercialAutoPolicySample.Id == null);


            //Get Audit Id Prefix

            Schema.DescribeSObjectResult dsr = Audit__c.sObjectType.getDescribe();
            this.auditIdPrefix = dsr.getKeyPrefix();   // Compile Error: Class static variable cannot be accessed via object instance at line 26 column 13 
            
            //Get Audit Id
            Id auditId = this.AuditCommercialAutoPolicySample.Audit__c;
                
            if (auditId == null) {
                string param1 = ApexPages.currentPage().getParameters().get('AccId');
                
                if (isAuditId(param1)) {
                    auditId = param1;
                }
                else {              
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Invalid Audit Id. Please contact the help desk with this error'));
                }
                 
            }

            //Load Audit Record
            List<Audit__c> audits = queryAudits(auditId);
            if (audits.isEmpty() == true) {
            
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'No records were found. Please contact the help desk with this error'));                          
    
            }
            else if (audits.size() > 1) {
            
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'More than 1 record found. Please contact the help desk with this error'));
            
            }
            else {
                this.Audit = audits[0];
                this.AuditCommercialAutoPolicySample.Audit__c = this.Audit.Id;
                if (this.IsNew) {
                    //Load defaults from audit template only for new samples.
                    //this.AuditCommercialAutoPolicySample.Insured_State_Location__c = this.Audit.Default_Insured_State__c;
                    //this.AuditCommercialAutoPolicySample.Default_Liability_Limits__c = this.Audit.Minimum_BI_Limits_Only__c;
                    //this.AuditCommercialAutoPolicySample.Other_Liability_Limit__c = this.Audit.Other_Minimum_BI_Limits_Only__c;
                    
                }
               
            }
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
    }

    //Public Methods



    //save and return user back to the audit .

    public PageReference saveAndReturn() {
        PageReference pageRef = null;
                
        try {
            PageReference saveRef = stdController.save();
            if (saveRef != null) { 
                    pageRef = new PageReference('/' + this.Audit.Id);
                    pageRef.getParameters().put('inline','0');
                    pageRef.setRedirect(true);
            }
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }

        return pageRef;
    }
    
    
    //just return user back to the audit .

    public PageReference ReturnMe() {
        PageReference pageRef = null;
        
        try {              
              pageRef = new PageReference('/' + this.Audit.Id);
              pageRef.getParameters().put('inline','0'); 
              pageRef.setRedirect(true);            
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }

        return pageRef;
    }

   
    //Private Methods
    private boolean isAuditId(string value) {
        boolean isValid = false;

        if (value != null && value.length() >= 15 && value.length() <= 18) {
            isValid = value.startsWith(auditIdPrefix);
        }

        return isValid;
    }

    private List<Audit__c> queryAudits(Id auditId) {
        List<Audit__c> audits = new List<Audit__c>();

        if (auditId != null) {
            audits = [SELECT 
                        Id
                        , Name
                        , Policy_Information__c
                        , Policy_Number__c
                        , Prior_Carrier__c
                        , Expiring_Premium__c
                        , Reinstatement_Information__c
                        , Insured_Location__c
                        , Agent_Information__c
                        , Agent_City__c
                        , Agent_Name__c
                        , Driver_Information__c
                        , Age__c
                        , Gender__c
                        , Marital_Status__c
                        , Named_Insured_Add_Driver__c
                        , Occupation__c
                        , Business_Use__c
                        , Vehicle_Information__c
                        , Model_Year__c
                        , Vehicle_Type__c
                        , ISO_Symbol__c
                        , Annual_Miles__c
                        , Limit_Information__c
                        , Liability_Limits__c
                        , UM_Limits__c
                        , UIM_Limits__c
                        , UM_UIM_Limits__c
                        , PIP_Limits__c
                        , PIP_Deductible__c
                        , APD_Deductible_Vehicle__c
                        , Premium__c
                        , Rating_Information__c
                        , MVR_Violations__c
                        , Policy_Discounts__c
                        , Rating_Tier__c
                        , Credit_Scoring__c
                        , Telematics_UBI__c
                        , Loss_Information__c
                        , CLUE_Report__c
                        , Prior_Carrier_Loss_Experience__c
                        , Company_Loss_Experience__c
                        , Individual_Loss_Detail__c
                        , General_Information__c
                        , Signed_Application__c
                        , Vehicle_Photo_Information__c
                        , Proof_of_Ownership__c
                        , Other_Policies__c
                        , UW_Guidelines_Followed__c
                        , Risk_Management_Standards__c
                        , Personal_Auto_Product__c
                        , Default_Insured_State__c
                        , Minimum_BI_Limits_Only__c
                        , Other_Minimum_BI_Limits_Only__c
                        , MGA_Name__c
                        , Insured_Name__c
                        , Effective_Date__c
                        , Policy_Term__c
                        , Insureds_Primary_Location__c
                        , Other_Garaging_Locations__c
                        , Agent_Commission__c
                        , MCS_90_Endorsement__c
                        , Signed_UM_UIM_Rejection__c
                        , Other_Lines_of_Business_Written__c
                        , SIR__c
                        , Thirty_Day_Policy_Issuance__c
                        , Symbols_Appropriate__c
                        , Comprehensive__c
                        , Collision__c
                        , Type_of_Operations__c
                        , Type_of_Goods_Hauled__c
                        , Type_of_Service__c
                        , Radius_of_Operations__c
                        , Operating_Environment__c
                        , Unit_Count_by_Vehicle_Type__c
                        , Number_of_Drivers__c
                        , Driver_List_Updated__c
                        , Driver_Information_in_File__c
                        , Driver_Surcharge__c                        
                        , Court_Documents__c
                        , Excluded_Drivers__c
                        , Loss_Activity__c
                        , Inspection_Report_in_File__c
                        , Third_Party_CAB_SAFER_Other__c
                        , Company_Financials_Reviewed__c
                        , IRPM_Worksheet_Questions__c
                        , Questions_Posed_of_Agent__c
                        , Underwriting_Checklist__c
                        , Facultative_Reinsurance__c
                        , Properly_Classified_Rated__c
                        , File_Comments__c
                        , Operations__c
                        , Limits_Deductibles_Premium__c
                                                
                              
                FROM 
                    Audit__c 
                WHERE 
                    Id = :auditId];
        }

        return audits;
    }
}


 
SarfarajSarfaraj
Rick, The following code works for me. Check if this meets your requirement,
function checkNumbersOps() {
    var val1 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value1}") != null)
		val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
	if(isNaN(val1))
		val1 = 0;
	var val2 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value2}") != null)
		val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
	if(isNaN(val2))
		val2 = 0;
	var tot = val1 + val2;
    if (tot < 100 || tot > 100)  
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations not equal to 100.';
    }
	else
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations equal to 100.'; 
    }
}

 
This was selected as the best answer
Rick MacGuiganRick MacGuigan
Akram, thanks for this. Interesting that isNaN comes into play. The fields in salesforce are of type 'Percent.' Is this causing a blank entry to show as not being a number type ?  I do need to test for three conditions. Am I correct in these assumptions ? Just trying to understand the result values.
  1. the field is rendered and 'has' a value entered in it.
  2. the field is rendered but has 'no' value entered in it, thus the value is considered a NaN ?
  3. the field is 'not' rendered, thus it is null ? 
SarfarajSarfaraj
Yes your assumptions are correct. Just to clarify, NaN is produced by the parseInt method. This gives NaN if the argument is blank, null or text.
Rick MacGuiganRick MacGuigan
Akram, thanks. I think the key was testing NaN. At first I though to just remove the currency type on the fields and go to a number. But then a user could possibly enter and alpha numeric (believe it or not :) ) as 20 percent. In that case the ParseInt and testing for NaN actually works in out favor here. 

Thanks again for all your help ! 
Rick MacGuiganRick MacGuigan
Akram, we discussed using iQuery before. What would your solution below look like in iQuery ? I'm seriously thinking of abandoning javascript. The jQuery library is part of our static resources. 
 
function checkNumbersOps() {
    var val1 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value1}") != null)
		val1 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value1}").value);
	if(isNaN(val1))
		val1 = 0;
	var val2 = 0;
	if(document.getElementById("{!$Component.page.form1.block1.section2.value2}") != null)
		val2 = parseInt(document.getElementById("{!$Component.page.form1.block1.section2.value2}").value);
	if(isNaN(val2))
		val2 = 0;
	var tot = val1 + val2;
    if (tot < 100 || tot > 100)  
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations not equal to 100.';
    }
	else
	{
		document.getElementById('{!$Component.page.form1.block1.section2.answerOperation}').innerHTML = 'Percent Radius of operations equal to 100.'; 
    }
}

 
SarfarajSarfaraj
Abandoning javascript!!! Please don't do that. I love javascript. LOL.

Here is the solution using jQuery. I took the liberty to optimize and compress the code as well,
function checkNumbersOps()
{
    var val1 = parseInt($("[id$='value1']").val());
	var val2 = parseInt($("[id$='value2']").val());
	var tot = (isNaN(val1) ? 0 : val1) + (isNaN(val2) ? 0 : val2);
	$("[id$='answerOperation']")
		.html(tot != 100 ? 'Percent Radius of operations not equal to 100.' 
		: 'Percent Radius of operations equal to 100.');
}
It is assumed that all id attribute values are unique throughout the page.
Rick MacGuiganRick MacGuigan
Thanks Akram. Appreciate the compression.