我对JS不太有经验。我在HTML中有两个输入字段,第一个用户输入要提取的金额,数据进入JavaScript,它减去0.00200000并在第二个HTML输入字段(只读字段)中显示: HTML:-
function calculate() {
var myBox1 = document.getElementById('ant').value;
var myBox2 = 0.00200000;
var result = document.getElementById('bank').value;
var numb = myBox1 - myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
<div class="wrap-input100 validate-input">
<p>Amount</p><input class="input100" type="text" name="amount" id="ant" placeholder="Amount to Send" oninput="calculate()">
<span class="focus-input100"></span>
<span class="symbol-input100">
</span>
</div>
<span class="login100-form-title">
Tx Fee:-0.00200000 LiteCoin (LTC)
</span>
<br>Your receive: - <input class="input100" type="text" id="bank" placeholder="Amount you receive" oninput="calculate()" readonly>
<input type="submit" name="submit" value="Withdraw">
当我将值放在页面第二个字段的第一个输入字段中时,永远不会获得任何值
答案 0 :(得分:2)
一个小错误:
var result = document.getElementById('bank').value;
需要成为
var result = document.getElementById('bank');
result
需要表示元素本身,而不是其值。否则,您将无法更改其值。
严格来说,您还应该使用parseFloat()
来避免JS认为您的“ ant”文本框中的值是字符串,并将其视为字符串。幸运的是,在这种情况下,您要针对固定值进行操作,但是如果您尝试将两个文本框值(两个字符串)相减,则会遇到更大的问题。
“ bank”元素中的oninput="calculate()"
也是多余的。由于该字段是只读字段,因此永远不会有任何用户输入来触发该功能。
function calculate() {
var myBox1 = parseFloat(document.getElementById('ant').value);
var myBox2 = 0.00200000;
var result = document.getElementById('bank');
var numb = myBox1 - myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
<div class="wrap-input100 validate-input">
<p>Amount</p><input class="input100" type="text" name="amount" id="ant" placeholder="Amount to Send" oninput="calculate()">
<span class="focus-input100"></span>
<span class="symbol-input100"></span>
</div>
<span class="login100-form-title">Tx Fee:-0.00200000 LiteCoin (LTC)</span>
<br>Your receive: -
<input class="input100" type="text" id="bank" placeholder="Amount you receive" readonly>
<input type="submit" name="submit" value="Withdraw">
答案 1 :(得分:1)
您的代码中有两个问题,第二个字段从未获得任何值:
document.getElementById('bank').value
应该仅是document.getElementById('bank')
,以便对result
的{{1}}变量赋值适用于result.value
parseFloat()
来解析您在第一个文本框中输入的数字作为浮点数,假设用户可以输入浮点值。这是因为当您使用JavaScript从文本框中读取值时,该值被视为String
类型,对于数字计算,您需要将该值转换为有效的Number
类型。
function calculate() {
var myBox1 = parseFloat(document.getElementById('ant').value);
var myBox2 = 0.00200000;
var result = document.getElementById('bank');
var numb = myBox1 - myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
<div class="wrap-input100 validate-input">
<p>Amount</p><input class="input100" type="text" name="amount" id="ant" placeholder="Amount to Send" oninput="calculate()">
<span class="focus-input100"></span>
<span class="symbol-input100">
</span>
</div>
<span class="login100-form-title">
Tx Fee:-0.00200000 LiteCoin (LTC)
</span>
<br>Your receive: - <input class="input100" type="text" id="bank" placeholder="Amount you receive" oninput="calculate()" readonly>
<input type="submit" name="submit" value="Withdraw">