我的求和函数错误,什么也不显示

时间:2018-09-30 11:36:51

标签: javascript html

这是我的JavaScript代码 我使用total来计算diskon,然后使用total,diskon和bayar来计算kembali。

<script type="text/javascript">    
function sum() {
      var total = document.getElementById('txtTotal').value;
      if (total >= 75000) {
        var diskon = parseInt(total) * 0.15;
        document.getElementById('txtDiskon').value = diskon;
      } else if (total >= 50000 & <=74999) {
        var diskon = parseInt(total) * 0.10;
        document.getElementById('txtDiskon').value = diskon;
      } 
      else if (total >= 25000 & <=49000) {
        var diskon = parseInt(total) * 0.05;
        document.getElementById('txtDiskon').value = diskon;
      } 
      else if (total >= 0 & <=24999) {
        var diskon = 0;
        document.getElementById('txtDiskon').value = diskon;
      }
      var bayar = document.getElementById('txtBayar').value;
      var kembali = parseInt(bayar) - (parseInt(total) - parseInt(diskon));

      if (!isNaN(kembali)) {
         document.getElementById('txtKembali').value = kembali;
      }
</script>

这是我的html代码

<input name="total" id="txtTotal" onkeyup="sum();" type="text"/>
<input name="diskon" id="txtDiskon" onkeyup="sum();" type="text" />
<input name="bayar" id="txtBayar" onkeyup="sum(); "type="text" />
<input name="kembali" id="txtKembali" type="text"/>

问题是,当我的JavaScript代码显示为“ else if”时,它没有显示“ diskon”,则没有更多错误。现在我不知道该错误在哪里,请帮助我修复该错误

1 个答案:

答案 0 :(得分:1)

将您的condition total >= 50000 && total <=74999 rather than total >=50000 & <= 74999.更新为其他条件之间的其他条件。看看[&&运算符] [1]

function sum() {
      var total = document.getElementById('txtTotal').value;
      if (total >= 75000) {
        var diskon = parseInt(total) * 0.15;
        document.getElementById('txtDiskon').value = diskon;
      } else if (total >= 50000 && total <=74999) {
        var diskon = parseInt(total) * 0.10;
        document.getElementById('txtDiskon').value = diskon;
      } 
      else if (total >= 25000 && total <=49000) {
        var diskon = parseInt(total) * 0.05;
        document.getElementById('txtDiskon').value = diskon;
      } 
      else if (total >= 0 && total <=24999) {
        var diskon = 0;
        document.getElementById('txtDiskon').value = diskon;
      }
      var bayar = document.getElementById('txtBayar').value;
      var kembali = parseInt(bayar) - (parseInt(total) - parseInt(diskon));

      if (!isNaN(kembali)) {
         document.getElementById('txtKembali').value = kembali;
      }
}
    <input name="total" id="txtTotal" onkeyup="sum()" type="text">
    <input name="diskon" id="txtDiskon" onkeyup="sum()" type="text" >
    <input name="bayar" id="txtBayar" onkeyup="sum()" type="text" >
    <input name="kembali" id="txtKembali" type="text">

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND