-2

I'm a beginner in JavaScript/jQuery and I am designing my first app using jQuery Mobile.

It is a basic calculator used for spectroscopic calculations.

I have 3 fields: You enter your values in the first and second field and I compute a number that appears in the third field. I used the keyup function to have real-time calculations performed.

The feature I would like to add is after the calculation is performed and appears in the third field that you can modify the third field to see the second field change (it would do the inverse calculation. The first field would remain the same)

What is the best way to do this in JavaScript? In my example I performed my inverse calculation but don't know how to display it back.

HTML

<div data-role="content" class="page11" >
    <div data-role="fieldcontain">
        <label for="l0">Excitation</label>
        <input type="text" name="l0" id="l0" data-clear-btn="true" value="">
        <label for="l1">Signal</label>
        <input type="text" name="l1" id="l1" data-clear-btn="true" value="">
        <label for="l2">Shift</label>
        <input type="text" name="l2" id="l2" data-clear-btn="true" value="">    
    </div>

Javascript

$('input').keyup(function () {

var l0 = parseFloat($('#l0').val()) || 0;
var l1 = parseFloat($('#l1').val()) || 0;
var dw1 = (l0 * l1)/2 || 0;
var dw = dw1.toFixed(2);
document.getElementById("l2").value = dw;

/* Inverse calculation */

var dw2 = parseFloat($('#l3').val()) || 0;
var l1_22 = 2 * dw2 / l0;
var l1_2 = l1_22.toFixed(2);


});

Thank you

Ry-
  • 209,133
  • 54
  • 439
  • 449

1 Answers1

1

http://jsfiddle.net/6RrVG/

I whipped this up:

html

<p>F: <input type="text" name="f" value="50.0" /></p>
<p>=</p>
<p>m: <input type="text" name="m" /></p>
<p>&times;</p>
<p>a: <input type="text" name="a"  /></p>

jQuery:

var $f = $('input[name=f]');
var $m = $('input[name=m]');
var $a = $('input[name=a]');
$m.on('keyup',function() {
    var f = +$f.val();
    var m = +$m.val();
    $a.val(f/m).toFixed(1);
});
$a.on('keyup',function() {
    var f = +$f.val();
    var a = +$a.val();
    $m.val(f/a).toFixed(1);
});

Attach keyup handlers to the inputs and do the calculations specific to each one.

Joe Frambach
  • 26,300
  • 10
  • 69
  • 98
  • I modified my code and used yours, it works perfectly! Thank you. – Nadacambia Jul 15 '13 at 17:58
  • Little question : I added another field to perform another calculation using the result of a, but I can't make it appear. It seems like it's a problem in selecting the value of a..? Also .toFixed doesn't work for fixing the decimals? – Nadacambia Jul 15 '13 at 20:41
  • toFixed problem was my fault, sorry. Here's an update: http://jsfiddle.net/6RrVG/1/ – Joe Frambach Jul 15 '13 at 21:09
  • I'm not sure what you mean with the other field. Update your question with a jsfiddle. – Joe Frambach Jul 15 '13 at 21:10