【问题标题】:how do I return form inputs and update javascript variables in running total calculator如何在运行总计计算器中返回表单输入并更新 javascript 变量
【发布时间】:2016-04-23 21:15:53
【问题描述】:

我正在尝试构建一个计算器,它根据预定义输入的总和计算总数。用户可以随时更改输入,总数会自动更新。

到目前为止,我已经设法创建了一个计算器,它采用预定义的输入变量并显示总数,但是当用户在表单中输入新变量时,我很难让总数更新。

我尝试了几种不同的方法来从表单返回输入并替换全局输入变量(“input1”和“input2”),但它们没有奏效。迈克,任何帮助将不胜感激。

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<br>TOTAL: <div id="chkTotal"></div>
<br>
<input type="text" name="input1" id="input1"/>
<input type="button" value="Change input 1" onclick="GetTotal(this)"/>
<br>
<br>
<input type="text" name="input2" id="input2"/>
<input type="button" value="Change input 2" onclick="GetTotal(this)"/>

<script>
  var input1 = 11692;
  var input2 = 13

$(document).ready(function() {
  GetTotal();
  SetInputVariables();
});

function GetTotal(txtBox) {
  var total = 0;
  document.getElementById("input1").value = input1;
  document.getElementById("input2").value = input2;
  $('input:text').each(function(index, value) {
    total += parseInt($(value).val() || 0);
  });

  $("#chkTotal").html(total);
}
</script>

【问题讨论】:

  • 如果您提供JsFiddle,对其他人来说总是更容易

标签: javascript


【解决方案1】:

您不断地用预定义的值覆盖输入框值。只运行一次预填充代码:

var input1 = 11692;
var input2 = 13;

$(document).ready(function() {
  document.getElementById("input1").value = input1;
  document.getElementById("input2").value = input2;
  GetTotal();  
});

function GetTotal() {
    var total = 0;

    $('input[type=text]').each(function(index, value) {
      total += parseInt($(value).val() || 0);
    });

    $("#chkTotal").html(total);
}

GetTotal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
TOTAL:
<div id="chkTotal"></div>
<br>
<input type="text" name="input1" id="input1" onkeyup="GetTotal()" />
<br>
<br>
<input type="text" name="input2" id="input2" onkeyup="GetTotal()" />

注意:为输入添加 onkeyup 监听器,而不是为每个输入添加外部按钮

【讨论】:

  • 谢谢 - 这正是我想要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多