How can I subtract two text inputs from the main input? For example if I inserted 100
in the total
input and then inserted 20
in v1
and 30
in v2
, the total
input should change to 50
. This what I've tried
function updateDue() { var val1 = parseInt(document.getElementById("v1").value); var val2 = parseInt(document.getElementById("v2").value); var ansD = document.getElementById("total"); ansD.value = ansD.value - val1 - val2; }
<input id="total" type="text " > <input id="v1" type="text" onchange="updateDue()> <input id="v2" type="text" onchange="updateDue()>
function updateDue(){
var first = $('#v1').val();
var second = $('#v2').val();
var before = $('#total').val();
var total=parseInt(before)-(parseInt(first)+parseInt(second));
$('#total').val(total);
}
<input id="total" type="text">
<input id="v1" type="text">
<input id="v2" type="text">
<button type="button" onclick="update()">Update</button>
<script>
function update() {
var total = parseInt(document.getElementById("total").value, 10);
var value1 = parseInt(document.getElementById("v1").value, 10);
var value2 = parseInt(document.getElementById("v2").value, 10);
document.getElementById("total").value = total - (value1 + value2);
}
</script>
Working example: https://jsfiddle.net/md9ebo00/5/
I would not suggest using onchange="update"
as an attribute for the two value fields, as when you type in the first value, you will wipe out your original total before you've typed in the second value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.