如何计算总数?

时间:2018-12-21 21:23:13

标签: javascript

我的代码遇到问题,无法解决。我有2个函数,第一个函数计算合计总额,第二个函数计算合计总额(如果用户编写了折扣代码,它将显示折扣合计总额)。但是我不知道如何从合计中获取并调用正确的值以将其保留在第二个函数中以计算折扣,因为它的金额始终显示为0。 TOTAL用于第一个函数,JavaScript代码用于第二个函数。

total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;

function discount(coupon) {
  var yCoupon = "winner1";
  var price = Number(document.getElementById('total').innerHTML);
  var amount;
  var input = document.getElementById('discount').value;

  if (input == coupon) {
    amount = price || 0 * 0.25;
    document.getElementById("Offerprice").innerHTML = amount;

  } else {
    alert("Invalid");
  }
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

2 个答案:

答案 0 :(得分:0)

像这样吗?

function discount() {
    var coupon = "winner1";
    var price = Number(document.getElementById('total').value); 
    var input = document.getElementById('discount').value;
	
    if (input == coupon) {
       var amount = price * (1 - .25)  // 25% off coupon
       document.getElementById("Offerprice").innerHTML = amount;
    } else {
       document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
    }
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()">  discount</button>

<p><span id ="Offerprice"></span></p>

答案 1 :(得分:0)

您的代码中有几个问题。这是一个工作版本。我将总数硬编码为仅用于测试,因为我不知道门票的HTML:

var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;

function discount() {
  var coupon = "winner1";
  var price = Number(document.getElementById('total').innerHTML);
  var input = document.getElementById('discount').value;

  if (input == coupon) {
    var amount = price * 0.75; //discount of 25%
    document.getElementById("Offerprice").innerHTML = amount;

  } else {
    alert("Invalid");
  }
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>