简体   繁体   中英

Run JavaScript Function onkeyup not working

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?

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();
}

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> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM