javascript添加输入字段

javascript on input field addition

本文关键字:字段 输入 添加 javascript      更新时间:2023-09-26

//// JavaScript function to add input values display into another input field 
function calculate() {
  var x = document.getElementById('fee_selector_holder').value;
  var y = document.getElementById('content').value;
  var result = document.getElementById('result');
  var myResult = x + y;
  result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">

我给输入字段的值,它的添加连接,但没有添加。请在输入函数上验证它是正确的还是错误的。一旦验证,然后回答我这是我的问题。

您有字符串,这就是为什么它是串联的。使用以下项生成整数:http://www.w3schools.com/jsref/jsref_parseint.asp

而且效果会很好。

首先,当您从DOM中读取值时,它们将被读取为字符串。您必须使用parseIntparseFloat将字符串转换为整数。

其次,+运算符有一个覆盖函数,用于字符串作为串联运算符。

另外请注意,我使用了.value || 0。这里,如果值不存在,对其执行算术运算将返回NaN,因此添加默认值(0)。

//// JavaScript function to add input values display into another input field 
function calculate() {
  var x = document.getElementById('fee_selector_holder').value || 0;
  var y = document.getElementById('content').value || 0;
  var result = document.getElementById('result');
  var myResult = parseInt(x) + parseInt(y);
  result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">

您必须将输入值解析为整数,因为默认情况下所有输入值都是字符串:

//// JavaScript function to add input values display into another input field 
function calculate() {
  var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank
  var y = document.getElementById('content').value || 0; // default value 0 if input is blank
  var result = document.getElementById('result');
  var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here 
  result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">

您应该将属性添加到result

result.setAttribute("value", myResult);