View Full Version : Auto calculate multiply and subtract

02-28-2012, 09:13 AM
Hi all...

i need to auto calculate 3 fields and store the result in 2 fields:

field 3 = field 1 * field 2
field 5 = (field 1 * field 2) - field 4 or field 3 - field 4

so far i'm trying to modify an existing code but i'm still can't get it working correcly

<script type="text/javascript">
function compute(inputObj, otherInputID, multiID, subID, diffID) {
var otherObj = document.getElementById(otherInputID)
var multiObj = document.getElementById(multiID)
var subObj = document.getElementById(subID)
var diffObj = document.getElementById(diffID)

var v1=inputObj.value
var v2=otherObj.value
var v3=multiObj.value
var v4=subObj.value

var val1 = v1=="" ? 0 : parseFloat(v1) // convert string to float
var val2 = v2=="" ? 0 : parseFloat(v2)
var val3 = v3=="" ? 0 : parseFloat(v3)
var val4 = v4=="" ? 0 : parseFloat(v4)

multiObj.value = val1 * val2
diffObj.value = (val1 * val2)-val4



Value 1: <input id="txt1" type="text" onKeyUp="compute(this, 'txt2', 'addres', 'subtract', 'mulres')">
<br />
Value 2: <input id="txt2" type="text" onKeyUp="compute(this, 'txt1', 'addres', 'subtract', 'mulres')">
<br />
Added Result: <input id="addres" type="text">
<br />
substract: <input id="subtract" type="text" onKeyUp="compute('txt1', 'txt2', 'addres', this, 'mulres')">
<br />
Multiplied Result: <input id="mulres" type="text">

my problem is the Multiplied Result field not automatically change the result when i enter value in subtract field. it will change if i retype the value in field 1 and 2.
Hope somebody can help me.

Thank in advance

02-28-2012, 09:38 AM
The problem is your choice of parameters for the compute() function. You should select either id string or the element object and stick to it. Better yet: Do not provide any parameter, because compute will always need the same (fixed) set of fields that can easily be determined without parameters

See this example (http://jsbin.com/iqagog) for a working version. If you hover your mouse over the example page, you'll notice a button "Edit in jsbin.com" on the top right corner. Using this button you can view and edit the full code of the example (HTML and Javascript)

02-28-2012, 10:36 AM
thank you very much devnull69...it's working like a charm

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum