peter rose
peter rose

Reputation:

javascript math equation

I have two form fields money and years that need to output a number into a third field cv .

Ideally while the first numbers are being entered but I'm OK with it happening after a button is pressed as well

<FORM name="salary">
    <input type="number" size=12 name="money"> 
    <input type="number" size=12 name="years"> 
    <input type="number" size=12 name="cv"> 
</FORM>

The math involved would be the following.

(money * years) - (money * years) x = cv

Where:

Upvotes: 1

Views: 7352

Answers (4)

Ilya Birman
Ilya Birman

Reputation: 10072

Do the math:

(money * years) - (money * years) x = cv
(money * years) x = (money * years) - cv
x = ((money * years) - cv) / (money * years)
x = 1 - cv / (money * years)

Get jQuery at http://jquery.com/

Update your code like this (notice that name → id):

<script type="text/javascript" src="jquery.js"></script>
<input type="number" size="12" id="money" />
<input type="number" size="12" id="years" />
<input type="number" size="12" id="cv" />
<div id="result"></div>
<script type="text/javascript">
  $ ('input').bind ('input change keyup keydown keypress', function () {
    $ ('#result').val (
       1 - $ ('#cv').val () / ($ ('#money').val () * $ ('#years').val ())
    )
  })
</script>

Upvotes: 0

Sophie Alpert
Sophie Alpert

Reputation: 143124

You can use jQuery, in which case it'll be something like this:

var money = parseFloat($("#money").val());
var years = parseInt($("#years").val(), 10);
var x = [0.00, 0.20, 0.45, 0.60, 0.65, 0.75][years-1];

$("#cv").val((money*years)*(1-x));

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 1403

Your going to want to put an onKeyUp() event on both of the fields people enter the data into and call a function something like what follows, in addition add an id to each field as used in the function. If you are not using prototype or jquery you need to use getElementById('var') in place of the $('var')

function calculateAndSetCV()
{
    money = parseFloat($('money').val());
    years = parseInt($('years').val());
    cv = 0;

    if(years == 1)
    {
        cv = (money * years) - (money * years)0;
    }

    $('cv').val(cv);
}

Upvotes: 0

Dave Swersky
Dave Swersky

Reputation: 34810

Breaking the problem down, you need to know how to use javascript to:

  • Programmatically get the text entered into a textbox
  • Confirm that the textbox contains numerical data
  • Perform the math
  • Set the value of the third textbox

All that and much more can be found here.

Upvotes: 3

Related Questions