+ Start a Discussion
Swetha Sfdc1Swetha Sfdc1 

dynamically calculate the sum of 2 text fields using java script

Hi Friends thanks in  advance,
I have 3 custom objects named ( object1__c, Object2__c, Object3__c) with the controller named (Checking). I had wrote  a code for dynamically adding of text fields when user enter add button on vfpage. I need  object1__c+Object2__c should be displayed in Object3__c . I have used jquery and javascript but it is not reflecting in new fields when I Click add button.
Thanks,
Swetha
Alexander TsitsuraAlexander Tsitsura
Hi Swetha,

Please see example below
<apex:inputText value="{!field_1__c}" id="field_1" />
<apex:inputText value="{!field_2__c}" id="field_2" />
<apex:inputText value="{!field_3__c}" id="sum" onchange="sum('{!$Component.field_1}', '{!$Component.field_2}', '{!$Component.sum}')" />


<script type="text/javascript">
       function sum(field1Id, field2Id, sumId) {
             var field1= document.getElementById(field1Id);
             var field2= document.getElementById(field2Id);
             var sum= document.getElementById(sumId);

             sum.value = Number(field1.value) +  Number(field2.value);
       }
</script>


As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
Swetha Sfdc1Swetha Sfdc1
Hi Alex, Thanks for giving response,

I have placed the code what you have given but it is not refleting in third field.

Thanks,
Swetha
Alexander TsitsuraAlexander Tsitsura
Hi Swetha,

Can you share a bit of code? or you can try to catch error in brouser dev console, if u use Chrome press F12.

Thanks,
Alex
Abhishek BansalAbhishek Bansal
Hi Swetha,

Please try with the below code :
<script type="text/javascript">
   function sum(field1Id, field2Id) {
         var field1= document.getElementById(field1Id);
         var field2= document.getElementById(field2Id);
         assignToSum(field1.value + field2.value);
   }
</script>
<apex:actionFunction name="assignToSum" rerender="fields">
	<apex:param name="sum" value="" assignTo="{!field_3__c}"/>
</apex:actionFunction>
<apex:outputPanel id="fields">
	<apex:inputText value="{!field_1__c}" id="field1" />
	<apex:inputText value="{!field_2__c}" id="field2" />
	<apex:inputText value="{!field_3__c}"/>
</apex:outputPanel>
<input type="button" onclick="sum('{!Component.field1}','{!Component.field2}')">Add</input>
Let me know if there is any issue.

Thanks,
Abhishek
 
Swetha Sfdc1Swetha Sfdc1
Thanks for giving response friends

I am working on this Code https://developer.salesforce.com/forums/?id=906F00000005FpSIAU.
I need above functionality in this code.

Thanks,
Swetha
Parth SrivastavaParth Srivastava
hi abhishek...
what is  Component here in this line:-
<input type="button" onclick="sum('{!Component.field1}','{!Component.field2}')">Add</input>