Reputation: 2157
I got old code of my apps that using javascript to calculate something, the logic is if 1 textbox filled, another textbox automatic filled, and when the second textbox filled, that another textbox will return text1 - text2, maybe You can look at this fiddle:
HTML:
<label>Price Start</label>
<input type="number" class="form-control" placeholder="Total Harga Diberikan" required="required" name="price" onkeyup="calculate()" id="price" />
<br />
<label>Discount</label>
<input type="number" class="form-control" placeholder="Nominal Potongan" name="jmlvoucher" onkeyup="calculate()" id="jmlvoucher" />
<br />
<label>Total</label>
<input type="number" class="form-control" placeholder="Total yang harus dibayarkan" required="required" name="total" id="total" />
Javascript:
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
var sum=parseFloat(num1)-parseFloat(num2);
document.getElementById('total').value=sum.toString();
}
http://jsfiddle.net/n4anv5qn/2/
Already try to check error, but there's no error. Try to run it, it doesn't works. Any idea why?
Upvotes: 2
Views: 4529
Reputation: 333
There indeed is an error being generated as keyup is fired.
Uncaught ReferenceError: calculate is not defined
On JSFiddle you've chosen to put your JavaScript into the onLoad
function which is wrong. You should instead choose No Wrap
See http://jsfiddle.net/n4anv5qn/5/
As requested, this code is an example of how you can still calculate your Total if your Discount is not filled. Simply check to see if the value you grabbed from num2 is blank and set it to a default value.
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
if (num2 == '')
num2 = '0';
var sum=parseFloat(num1)-parseFloat(num2);
document.getElementById('total').value=sum.toString();
}
Upvotes: 3
Reputation: 1939
You should use onchange
instead of onkeyup
. Also put your scripts right before the closing body tag.
Here's how to do it:
<label>Price Start</label>
<input type="number" class="form-control"name="price" onchange="calculate()" id="price" />
<br />
<label>Discount</label>
<input type="number" class="form-control" onchange="calculate()" id="jmlvoucher" />
<br />
<label>Total</label>
<input type="number" class="form-control" required="required" name="total" id="total" />
<script>
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
var sum = parseFloat(num1) - parseFloat(num2);
document.getElementById('total').value = sum;
}
</script>
Upvotes: 0