16 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/myscript.js:
--------------------------------------------------------------------------------
1 | // define a function to perform our calculation.
2 | function calculate () {
3 | // retrieve the values from the amount and percentage fields
4 | // and store them in variables.
5 | var amount = $('#amount').val();
6 | var percentage = $('#percentage').val();
7 |
8 | // calculate the actual tip.
9 | var tip = amount * (percentage / 100);
10 |
11 | // also calculate the total.
12 |
13 | // Note the 'Number' function: amount is actually a string
14 | // and adding a number to a string just makes a longer
15 | // string, so we convert it to a number first.
16 | var total = Number(amount) + tip;
17 |
18 | // Store the values in the result fields
19 |
20 | // Note that we call the 'toFixed' function,
21 | // which is a property of all numbers. This
22 | // makes sure there are only two digits after
23 | // the decimal point.
24 | $('#tip').val( tip.toFixed(2) );
25 | $('#total').val( total.toFixed(2) );
26 |
27 | // submit event fucntions must return false,
28 | // to tell the browser not to load a new page.
29 | return false;
30 | }
31 |
32 | // attach our function to the form's submit event.
33 | $('#calculator').submit( calculate );
--------------------------------------------------------------------------------