Forums

calculate form

volker 03 Apr, 2009
need help...i want this form to calculate and save to database how can i do that? my programming skills aren't that good...
<head><title>JavaScript Loan Calculator</title></head>
<body bgcolor="white">
<!-- 
  This is an HTML form that allows the user to enter data and allows
  JavaScript to display the results it computes back to the user. The
  form elements are embedded in a table to improve their appearance.
  The form itself is given the name "loandata", and the fields within
  the form are given names such as "interest" and "years". These
  field names are used in the JavaScript code that follows the form.
  Note that some of the form elements define "onchange" or "onclick"
  event handlers. These specify strings of JavaScript code to be
  executed when the user enters data or clicks on a button. 
-->
<form name="loandata">
  <table>
    <tr><td colspan="3"><b>Enter Loan Information:</b></td></tr>
    <tr>
      <td>1)</td>
      <td>Amount of the loan (any currency):</td>
      <td><input type="text" name="principal" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr>
      <td>2)</td>
      <td>Annual percentage rate of interest:</td>
      <td><input type="text" name="interest" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr>
      <td>3)</td>
      <td>Repayment period in years:</td>
      <td><input type="text" name="years" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr><td colspan="3">
      <input type="button" value="Compute" onclick="calculate();">
    </td></tr>
    <tr><td colspan="3">
      <b>Payment Information:</b>
    </td></tr>
    <tr>
      <td>4)</td>
      <td>Your monthly payment will be:</td>
      <td><input type="text" name="payment" size="12"></td>
    </tr>
    <tr>
      <td>5)</td>
      <td>Your total payment will be:</td>
      <td><input type="text" name="total" size="12"></td>
    </tr>
    <tr>
      <td>6)</td>
      <td>Your total interest payments will be:</td>
      <td><input type="text" name="totalinterest" size="12"></td>
    </tr>
  </table>
</form>

<!--
  This is the JavaScript program that makes the example work. Note that
  this script defines the calculate() function called by the event
  handlers in the form. The function refers to values in the form
  fields using the names defined in the HTML code above.
-->
<script language="JavaScript">
function calculate() {
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    var principal = document.loandata.principal.value;
    var interest = document.loandata.interest.value / 100 / 12;
    var payments = document.loandata.years.value * 12;

    // Now compute the monthly payment figure, using esoteric math.
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);

    // Check that the result is a finite number. If so, display the results.
    if (!isNaN(monthly) && 
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {

        document.loandata.payment.value = round(monthly);
        document.loandata.total.value = round(monthly * payments);
        document.loandata.totalinterest.value = 
            round((monthly * payments) - principal);
    }
    // Otherwise, the user's input was probably invalid, so don't
    // display anything.
    else {
        document.loandata.payment.value = "";
        document.loandata.total.value = "";
        document.loandata.totalinterest.value = "";
    }
}

// This simple method rounds a number to two decimal places.
function round(x) {
  return Math.round(x*100)/100;
}
</script>
</body>
</html>
GreyHead 03 Apr, 2009
Hi volker,

Add this code below into the Form HTML box of your form and set "Load Chronoforms CSS/JS Files?" to Yes in the General Tab to make sure that the MooTools library is loaded.

Bob
<?php
$script = "
window.addEvent('domready', function() {
  function calculate() {
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    var principal = $('principal').value;
    var interest = $('interest').value / 100 / 12;
    var payments = $('years').value * 12;

    // Now compute the monthly payment figure, using esoteric math.
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);
    var payment = $('payment');
    var total = $('total');
    var totalinterest = $('totalinterest');
    // Check that the result is a finite number. If so, display the results.
    if (!isNaN(monthly) &&
      (monthly != Number.POSITIVE_INFINITY) &&
      (monthly != Number.NEGATIVE_INFINITY)) {

      payment.value = round(monthly);
      total.value = round(monthly * payments);
      totalinterest.value =
          round((monthly * payments) - principal);
    } else {
      // Otherwise, the user's input was probably invalid, so don't
      // display anything.
      payment.value = '';
      total.value = '';
      totalinterest.value = '';
    }
  }

  // This simple method rounds a number to two decimal places.
  function round(x) {
    return Math.round(x*100)/100;
  }
  $('compute').addEvent('click', calculate );
  $('principal').addEvent('change', calculate );
  $('interest').addEvent('change', calculate );
  $('years').addEvent('change', calculate );
});
";
$doc =& JFactory::getDocument();
$doc->addScriptDeclaration($script);
?>
<table>
    <tr><td colspan="3"><b>Enter Loan Information:</b></td></tr>
    <tr>
      <td>1)</td>
      <td>Amount of the loan (any currency):</td>
      <td><input type="text" name="principal" id="principal" size="12" ></td>
    </tr>
    <tr>
      <td>2)</td>
      <td>Annual percentage rate of interest:</td>
      <td><input type="text" name="interest" id="interest" size="12" ></td>
    </tr>
    <tr>
      <td>3)</td>
      <td>Repayment period in years:</td>
      <td><input type="text" name="years" id="years" size="12" ></td>
    </tr>
    <tr><td colspan="3">
      <input type="button" value="Compute" id='compute' " >
    </td></tr>
    <tr><td colspan="3">
      <b>Payment Information:</b>
    </td></tr>
    <tr>
      <td>4)</td>
      <td>Your monthly payment will be:</td>
      <td><input type="text" name="payment" id="payment" size="12" readonly='readonly' ></td>
    </tr>
    <tr>
      <td>5)</td>
      <td>Your total payment will be:</td>
      <td><input type="text" name="total" id="total" size="12" readonly='readonly'></td>
    </tr>
    <tr>
      <td>6)</td>
      <td>Your total interest payments will be:</td>
      <td><input type="text" name="totalinterest" id="totalinterest" size="12" readonly='readonly' ></td>
    </tr>
  </table>
volker 03 Apr, 2009
it works!! thanks...
DECHAUD Patrice 08 Jul, 2009
Hi!

I am a french user of Joomla and I'm a new user of Chronoform who's a very good tool for me to insert records in my database.

I have a problem and I've dont find any solution in tutorials on your site.

I need to calculate the contents of some fields and I do not know enough about php. I've found a post from volker, Fri Apr 03, 2009 3:38 pm. You gave to him a code and i tried to update it for me...

I've made a little multiplication, but I don't really understand the code.... :
http://90plan.ovh.net/~cftanse/TEST/index.php?option=com_chronocontact&Itemid=61

This is what I need : Show the compute values on the page before Submit.

May I ask your help?

Thank you in advance.

Best regards.

Patrice.
http://www.cftanse.fr
GreyHead 09 Jul, 2009
Bonjour Patrice,

I see that you have the first few boxes working OK. The rest will be very similar code.

I'm afraid that I don't see what should go into the boxes where you have "OR = B1 * C / OR = B2 * C" If you can explain exactly how the calculations should be done we may be able to help more.

Bob
DECHAUD Patrice 09 Jul, 2009
Hi Bob !
Thank you for the quick answer !
I've made a "logigramme" for this program, like I do for Visual Basic... You can find int in attachment. I understand better VB than PHP, but I hope to manage my own PHP codes in a few months.... With your help, because I'm a learner of it...

For resume :
Currently, I only obtain B1 = A * B

In the other boxes, the user MUST choose ONE and ONLY ONE type of Commission in the Form (XOR). In Percent : B, or In Package (Forfait) : B2

After, the computes are like this :
If B Choosen (currently case):
C1 = B1 * C
D = B1 + C1


If B2 Choosen :
C1 = B2 * C
D = B2 + C1


And after this, the last compute is always the same : E = A + D

Many thanks

And.. will Chronoform include automatic computing field in the future ? It'll be fine for many users to "start level" in PHP like me...

Regards
Patrice
Max_admin 12 Jul, 2009
Hi Patrice,

you can do these calculation in PHP and add the code in the onSubmit code after email box, in PHP you get a variable value in this case with this formula:

$_POST['variable_name']


Cheers
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
GreyHead 12 Jul, 2009
Hi Patrice,

If you do this calculation - as you have so far - in the browser, then you'll be using JavaScript, not PHP (which is used only on the server after the form results have been returned).

I think that there are four 'true' input fields:
Prix de vent ('prix')
Commission en pourcent ('comm_pc')
Commission forfait ('comm_ff')
Taux TVA ('tva')

Everything else is calculated. In the script I'm assuming that your inputs have the ids above (not the curren ones).

If you load the MooTools library it makes some of the JavaScript a little easier. It will be loaded automatically if you use ChronoForms Validation, ToolTips, etc.

These script start to get more complicated when you start to add in validation, formatting, etc, so this is just a rough sketch (not tested and will need de-bugging).
<?php
$script = "
  window.addEvent('domready', function() {
  calcComm = function() {
    // initialise some variables
    var prix = $('prix').value;
    var com_pc = $('com_pc').value;
    var com_ff = $('com_ff').value;
    var tva = $('tva').value;
    var comm = 0;
    var total = 0;
    // calculation
    if ( prix > 0 && tva > 0 ) {
      if ( com_pc > 0 ) {
         comm = prix*com_pc;
      } else if ( com_ff > 0 ) {
         comm = com_ff;
      } else {
         alert("Vous devez faire un choix");
         return;
      }
    tva = comm*tva;
    total = prix + comm + tva;
    // display the result
    $('total').setHTML(total);
  };
  // add events to the input fields to recalculate
  $('prix').addEvent('change', calcCom()); 
  $('com_pc').addEvent('change', calcCom());
  $('com_ff').addEvent('change', calcCom());
  $('tva').addEvent('change', calcCom());
  });
";
$doc =& JFactory::get Document();
$doc->addScript($script);
?>

Bob
DECHAUD Patrice 22 Jul, 2009
Hi Bob !

I was in holidays and away from any connection point for few days. Thank you for your answer, but I've reached my goal by the first way... With some brainstorms...

You can see the result here : http://90plan.ovh.net/~cftanse/TEST/index.php?option=com_chronocontact&Itemid=62

My code is :
<div class="form_item">
  <div class="form_element cf_heading">
    <h2 class="cf_text"> </h2>
  </div>
  </div>

<div class="form_item">
  <div class="form_element cf_text"> <span class="cf_text"><strong><em>DETAILS DE LA TRANSACTION</em></strong></span>
    <?php
    $script = "
    window.addEvent('domready', function() {
      function calculate() {
        // Déclaration des variables input
        var A = $('A').value;
        var B = $('B').value / 100;
        var C = $('C').value / 100;
		

        // Champs calculés
		
		//valeurs temporaires
		var calc_A = (A*1)
        var calc_B1 = (A*B);
        var calc_C1 = (calc_B1*C);
        var calc_D = (calc_B1+calc_C1);
        var calc_E = (calc_A+calc_D);
		
		//affectation des valeurs calculées 
		var B1 = $('B1');
		var C1 = $('C1');
		var D = $('D');
		var E = $('E');

		
        // Check that the result is a finite number. If so, display the results.
        if (!isNaN(calc_B1 ) &&
          (calc_B1 != Number.POSITIVE_INFINITY) &&
          (calc_B1 != Number.NEGATIVE_INFINITY)) {

          B1.value = round(calc_B1 );
          C1.value = round(calc_C1 );
          D.value = round(calc_D );
          E.value = round(calc_E );		  		  
        } else {
          // Otherwise, the user's input was probably invalid, so don't
          // display anything.
          B1.value = '';
          D.value = '';
          E.value = '';
        }
      }

      // This simple method rounds a number to two decimal places.
      function round(x) {
        return Math.round(x*100)/100;
      }
      $('compute').addEvent('click', calculate );
      $('A').addEvent('change', calculate );
      $('B').addEvent('change', calculate );
      $('C').addEvent('change', calculate );
	  
    });
    ";
    $doc =& JFactory::getDocument();
    $doc->addScriptDeclaration($script);
    ?>
</div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>A  	PRIX DE VENTE NET : *</strong></label>
    <input class="cf_inputbox required validate-number validate-currency-dollar" maxlength="150" size="20" title="Saisissez un montant" id="A" name="A" type="text" style="text-align:right" />
  
  €</div>
  <div class="cfclear"> </div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>B  	COMMISSION (EN %) : *</strong></label>
    <input class="cf_inputbox required validate-number" maxlength="150" size="10" title="Saisissez un nombre" id="B" name="B" type="text" style="text-align:right" />
  
  %</div>
  <div class="cfclear"> </div>
</div>

<div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>B1  	MONTANT COMMISSION
    HT :</strong></label>
    <input class="cf_inputbox" style="background-color:lightgrey;color:blue;text-align:right " maxlength="150" size="20" title="" id="B1" name="B1" type="text" readonly="readonly" />
    €
  <a class="tooltiplink" onClick="return false;"><img height="16" border="0" width="16" class="tooltipimg" src="components/com_chronocontact/css/images/tooltip.png"/></a>
				<div class="tooltipdiv">B1 : :: A * B</div>  
				<div class="cfclear"> </div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>C  	TAUX TVA SUR COMMISSION (%) : *</strong></label> 
    <input class="cf_inputbox required validate-number" style="background-color:lightgrey;color:blue;text-align:right" maxlength="150" size="10" title="Saisissez un nombre" id="C" name="C" type="text" value="19.6"/>
    %
  
  </div>
  <div class="cfclear"> </div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>C1  	MONTANT TVA SUR
    COMMISSION :</strong></label>
    <input class="cf_inputbox" style="background-color:lightgrey;color:blue;text-align:right" maxlength="150" size="20" title="" id="C1" name="C1" type="text" readonly="readonly" />
    €
  <a class="tooltiplink" onClick="return false;"><img height="16" border="0" width="16" class="tooltipimg" src="components/com_chronocontact/css/images/tooltip.png"/></a>
				<div class="tooltipdiv">C1 : :: B1 x C</div>  
  
  </div>
  <div class="cfclear"> </div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>D  	TOTAL TTC (COMMISSION
    + TVA) :</strong></label>
    <input class="cf_inputbox"  style="background-color:lightgrey;color:blue;text-align:right" maxlength="150" size="20" title="" id="D" name="D" type="text" readonly="readonly" />
    €
  <a class="tooltiplink" onClick="return false;"><img height="16" border="0" width="16" class="tooltipimg" src="components/com_chronocontact/css/images/tooltip.png"/></a>
				<div class="tooltipdiv">D : :: B1 + C1</div>  
  </div>
  <div class="cfclear"> </div>
</div>

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 260px;"><strong>E  	PRIX DE VENTE
    TTC :</strong></label>
    <input class="cf_inputbox"  style="background-color:lightgrey;color:blue;text-align:right" maxlength="150" size="20" title="" id="E" name="E" type="text" readonly="readonly" />
    €
  <a class="tooltiplink" onClick="return false;"><img height="16" border="0" width="16" class="tooltipimg" src="components/com_chronocontact/css/images/tooltip.png"/></a>
				<div class="tooltipdiv">D : ::  A + D</div>  
  
  </div>
  <div class="cfclear"> </div>
</div>
<div class="form_element cf_textbox">
                  <input name="button" type="hidden" id='compute' value="" >
  <div class="cfclear"></div>
</div>

<div class="form_item"></div>


Can you help me now for obtain the numbers formatted like this : "1.000.000,00 €"

Thank you very much !!
GreyHead 22 Jul, 2009
Hi Patrice,

Excellent!

I Googled and found a number formatting function herethat should to the job.

Bob
DECHAUD Patrice 22 Jul, 2009
Hi Bob !

I like very much the sentence "I Googled" LOL.
Google is really a source of science !!

I haven't see this code in my searches, so I will try it immediatly.

Thanks to you and to Max... (I've read his answer after yours...).

I start to understand better php and js finally....

I will tell you later if it works !

Patrice.
DECHAUD Patrice 24 Jul, 2009
Hi Bob.

I'm sorry but I don't obtain a result... The big question for me was : "Where should I put this code ?"

I've tried the code on two ways :

First way : In the main code of my form ? Form code -> Main onLoad/View code -> Form HTML
(view attached picture) Absolutely no results...

Second way : (currently in use) : With the use of "onchange" event in the HTML and the script in the section Form JS
In the Form code -> Main onLoad/View code -> Form HTML ,
(view attached picture)
I modify the code for the Inputbox "A" like this :
.....<input class="cf_inputbox required validate-number validate-currency-dollar" maxlength="150" size="20" title="Saisissez un montant" id="A" name="A" type="text" style="text-align:right" onChange="this.value=Number.extend(this.value)" />.....


and after, in the Form code -> Main onLoad/View code -> Form JavaScript ,
I've put the code from your link (without any modification):
Number.extend({

	/*
	Property: numberFormat
		Format a number with grouped thousands.

	Arguments:
		decimals, optional - integer, number of decimal percision; default, 2
		dec_point, optional - string, decimal point notation; default, '.'
		thousands_sep, optional - string, grouped thousands notation; default, ','

	Returns:
		a formatted version of number.

	Example:
		>(36432.556).numberFormat()  // returns 36,432.56
		>(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
	*/

	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';
	
		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}


});


And the return value is : "undefined"...

I've read many posts on this error on Internet, it is because a value is not declared ??... but I don't know how to solve it...

You can see the result here :
http://90plan.ovh.net/~cftanse/TEST/index.php?option=com_chronocontact&Itemid=63

I need one more time your help...

Thank you very much.

Regards

Patrice.
http://www.cftanse.fr
GreyHead 25 Jul, 2009
Hi Patrice,

The JavaScript can go in the JavaScript box Ok (or use the Joomla addScriptDeclaration code). But to use it you need ot see the examples in the code

>(36432.556).numberFormat() // returns 36,432.56
>(36432.556).numberFormat(2, '.', ',') // returns 36,432.56


Bob
DECHAUD Patrice 27 Jul, 2009
Hi Bob.

I solved my problem myself... The formatting function was'nt good because after formatting the number, it was impossible to calculate with it...

I've found the function to have the possibility to calculate with the formatting numbers and it works !

You can see the result here :

http://90plan.ovh.net/~cftanse/TEST/index.php?option=com_chronocontact&Itemid=62

After Input 1 & 2, the format and the compute are applying on all the value.

I have now another question about the Date Time Picker. Is it a possibility to change it to French format ?

Currently, it works with the name of month in english, like July August etc....

Thanks a lot.

Regards

Patrice
GreyHead 27 Jul, 2009
Hi Patrice,

Well done, that looks good.

You can change the datepicker values - I just forget exactly how. In a thread a few weeks ago we worked out how to do it for someone else. I think that you can do it by adding an extra entry in the Date Fields Extras box at the end of the General Tab.

Bob
jun09bi 30 Aug, 2009
Hi,

Thanks for sharing all these tutorials. I'm still a newbie so i'm still confused with these kinds of things.

Regards,
Jun
Regroupement credits
jsadik 01 Jun, 2010
In the second post on this thread, what language are you using to calculate the values and dynamically enter them in the read-only fields. It looks like java script, is that correct?
This topic is locked and no more replies can be posted.