输入并使用它进行计算

时间:2014-01-09 17:22:25

标签: javascript jquery

我想以xxxx.xx或xx%的形式从用户输入折扣,并更改金额的计算方法。

//amount = mrp - discount (if discount is xxxx.xx)
    //amount = mrp - discount * mrp (if discount is xx%)

function doMath() {
  var mrp = parseInt(document.getElementById('inmrp').value);
  var discount = (document.getElementById('indiscount').value).String();
  var dis = discount[2];
  var di = discount[1];
  if (dis = '%' || di = "%") {
    discount = (parseInt(discount))/100;
    amount = mrp - mrp * discount;  
  } else {
    discount = parseInt(discount);
    amount = mrp - discount;
  }
  document.getElementById('outamount').value= amount ;
}

3 个答案:

答案 0 :(得分:0)

对象没有String功能,但您可能正在寻找toString()。但是它是不必要的,因为text类型的输入的value属性已经是字符串

var discount = document.getElementById('indiscount').value;

此外,检查最后一个字符是否为%符号而不是始终检查第三个字符可能更安全。

var isPercent = discount[discount.length - 1] === '%';

答案 1 :(得分:0)

尝试

var di = discount.substr(discount.length - 1);  
  if (di == "%") {
   ..........
   .....

jsfiddle here

答案 2 :(得分:0)

我使用函数indexOf来知道文本中是否有'%'。然后,如果它有一个子串来删除它。

function doMath() {
  var mrp = parseInt(document.getElementById('inmrp').value);
  var discount = document.getElementById('indiscount').value;
  if (discount.indexOf('%') != -1) {
    discount = discount.substring(0,discount.length)
    discount = (parseInt(discount))/100;
    amount = mrp - mrp * discount;  
  } else {
    discount = parseInt(discount);
    amount = mrp - discount;
  }
  document.getElementById('outamount').value= amount ;
}