Splendonia Splendonia - 1 year ago 104
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:


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;


<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 Source

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;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download