【问题标题】:Divide input fields with JavaScript用 JavaScript 划分输入字段
【发布时间】:2019-01-26 21:17:04
【问题描述】:

我有 3 个输入字段:

<input type="text" id ="v0" onkeyup="calculate()"><br>
<input type="text" id ="v1" onkeyup="calculate()"><br>
<input type="text" id="result" onkeyup="calculate()" readonly><br>

我要做的是计算第一个输入的数字除以第二个输入的数字并在第三个输入中显示。

function calculate(){
  var result = document.getElementById('result');
  var el, i = 0, total = 0; 
  while(el = document.getElementById('v'+(i++)) ) {
    el.value = el.value.replace(/\\D/,"");
    total = total + Number(el.value);
  }
  result.value = total;
  if(document.getElementById('v0').value =="" && document.getElementById('v1').value ==""){
    result.value ="";
  }
}

添加此输入值的代码工作正常,但我需要从输入字段中除值。
我试图用“/”替换“+”,但它破坏了功能。

【问题讨论】:

  • /替换+肯定不会减去!!!
  • 那么如何划分呢?

标签: javascript input field


【解决方案1】:

你可以试试这样更简单的方法:

function calculate () {
  var input1 = document.querySelector('#v0').value;
  var input2 = document.querySelector('#v1').value;
  if (input1 && input2) {
    document.querySelector('#result').value = (input1 / input2).toFixed(2);
  }
}

【讨论】:

    【解决方案2】:

    首先你必须使用 "-" 进行减法。但是如果你想执行除法,问题是在第一次迭代期间你的总为 0,它会是:

    iteration[1]: 0/anything = 0
    iteration[2]: 0/anything = 0
    and so on
    

    因此,如果要执行除法,则需要总计的初始值,它必须是第一个输入。 希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多