Create Calculation Form

upazupa 06 Jan, 2012
Hello,

I would like to create a form to make some calculations.

3 fields:
-Number1
-Number2
-Result

And when it calculates the sum of both Numbers.

I don't want to use a submit button, I would like an "onChange" event.
How can I achieve this? Maybe javascript code...

Thanks for any help.
Cheers
GreyHead 06 Jan, 2012
Hi upazupa,

JavaScript will let you do this. See this post for an example.

Bob
upazupa 16 Jan, 2012
Thanks Grey for your answer.

I tried this code:

window.addEvent('domready', function() {
  $('num1').addEvent('change', calculate);
  $('num2').addEvent('change', calculate);

function calculate() {
  $('res').value = parseInt($('num1').value) + parseInt($('num2').value);
};

});


And I have 2 events on my form:
-Load JS
-Show HTML

But nothing is happen on the field "res"...

Any idea?
Thanks in advance.
GreyHead 16 Jan, 2012
Hi upazupa,

Then you need to debug your code :-(

Bob
upazupa 17 Jan, 2012
Yup, that's true!

Now it's working after a debbuging🙂

But the result only appears after a refresh (f5), how can I make it everytime a textfield is changed without refresh the page?
GreyHead 17 Jan, 2012
Hi upazupa,

Hard to say without seeing the latest version of the code. Using the onChange events (as your previous example does) should run the function when one of those two inputs changes.

Bob
upazupa 17 Jan, 2012
I'm using the same code:

window.addEvent('domready', function() {
  $('num1').addEvent('change', calculate());
  $('num2').addEvent('change', calculate());

 function calculate() {
   $('res').value = parseInt($('num1').value) + parseInt($('num2').value);
 };

});


You can test it here:
http://contas.ementas.net/index.php/soma

Any idea?
GreyHead 17 Jan, 2012
Hi upazupa ,

There are some JavaScript errors on the page - they seemt o come from the Form but I can't see what is causing them :-(

Please take a Form Backup using the icon in the Forms Manager and post it here (as a zipped file) or PM or email it to me and I'll take a closer look.

Bob
GreyHead 17 Jan, 2012
Hi upazupa,

The problem was the () in 'change', calculate()

I fixed that and got rid of the NaN
window.addEvent('domready', function() {
  $('num1').addEvent('change', calculate);
  $('num2').addEvent('change', calculate);
});
function calculate() {
  var sum = parseInt( $('num1').value ) + parseInt( $('num2').value );
  if ( isNaN(sum) ) {
    sum = '';
  }
  $('res').value = sum;
};

Bob
This topic is locked and no more replies can be posted.