Splendonia Splendonia - 7 months ago 28
Javascript Question

calculate division of fields dynamically using Jquery or Javascript

I'm "trying" to figure out how to calculate a division between to fields dynamically to display in another field, the thing is, all examples I've seen are sums, and those used something like this:

$('#field').each(function(){....});
.

I can't do that because there's no way of know which is the dividend and which is the divisor. I tried using "bind", to try to attach the function to the field. It didn't work.

Also tried putting "onChange="CalcularSaldo()" on the input field; no luck, but mainly because i'm pretty sure my function is wrong:

<script type="text/javascript">
$(document).ready(function() {
function calcularSaldo() {
var costo = document.getElementById("costo_ad").value;
var vida = document.getElementById("vida_util").value;
document.getElementById("saldo_dep").value = costo / vida;
}
});</script>


Inputs:

<label for="costo_ad">Costo de Adquisicion</label>
<input name="costo_ad" type="text" id="costo_ad" class="round default-width-input" />

<label for="vida_util">Vida Util</label>
<input name="vida_util" type="text" id="vida_util" class="round default-width-input" />

<label for="saldo_dep">Saldo a Depreciar</label>
<input name="saldo_dep" type="text" id="saldo_dep" class="round default-width-input" disabled />


and the function should be something like this:

saldo_dep = costo_ad / vida_util

Answer

suppose we have the following fields

<input type="number" id="field1">
<input type="number" id="field2">

<span id="label"></span>

so, you'd want to attach the jquery function to some action on the fields, like after the user finishes entering text in either of the boxes

$("#field1, #field2").keyup( function(){

     var n1 = $("#field1").val();
     var n2 = $("#field2").val();

     var result = n2/n1;
     $("#label").text(result);


});

Example is in jsFiddle... http://jsfiddle.net/A3qat/5/