How to rewrite the below script to auto calculate the total price and total cost at the same time ??
Thank you very much for your help & support !
var x = 0;
var y = 0;
var z = 0;
function calc(obj) {
var e = obj.id.toString();
if (e == 'quantity') {
x = Number(obj.value);
y = Number(document.getElementById('unit_price').value);
} else {
x = Number(document.getElementById('quantity').value);
y = Number(obj.value);
}
z = x * y ;
document.getElementById('sub_price').value = z;
document.getElementById('update').innerHTML = z;
}
<form>
Quantity: <input type="number" id="quantity" name="quantity" value="1" onkeyup="calc(this)" required="required"/>
<br>
Unit Price:<input type="number" id="unit_price" onkeyup="calc(this)" name="unit_price" step="any" value="3" required="required" />
<br>
Total Price:<input type="number" id="sub_price" name="sub_price" step="any" value="" readonly required="required" />
<br><br>
Unit Cost:<input type="number" id="unit_cost" onkeyup="calc(this)" name="unit_cost" step="any" value="2" required="required" />
<br>
Total Cost:<input type="number" id="sub_cost" name="sub_cost" step="any" value="" readonly required="required" />
</form>
2
Answers
You can update your calc function as follows. Hopefully this will work:
You can delegate. I assume you will have more than one item