我有這個HTML和Java腳本。我設置爲自動顯示這3個輸入字段的總金額。但是如果我使用+(添加),它會給我錯誤的答案。如果我使用*(乘)或/(分開),我工作得很好。任何人請幫助!在HTML中添加數字值
這是我的HTML代碼。
</pre>
<tr>
<td><input type='number' id='amt1' name='amt1' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
<td><input type='number' id='amt2' name='amt2' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
<td><input type='number' id='amt3' name='amt3' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
<td><input type='number' id='total' name='total' class='form-control' readonly='readonly'></td>
</tr>
<pre>
我的繼承人Java腳本...
<script type="text/javascript">
function total_amount()
{
document.getElementById('total').value = document.getElementById('amt1').value + document.getElementById('amt2').value + document.getElementById('amt3').value
}
function numbersonly(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=27 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow)
if (unicode<48||unicode>57)
return false
}
}
</script>
</pre>
哪裏是你的HTML嗎? – 2014-10-02 06:11:16
爲什麼'「1」+「1」==「11」'?哦,你正在添加字符串... – RobG 2014-10-02 06:14:50
限制用戶對某些鍵的輸入不是用戶友好的,並且不會通過粘貼或其他方式停止輸入非數字,只是不要這樣做。您只關心用戶完成輸入後的價值,他們如何到達那裏取決於他們。 – RobG 2014-10-02 06:25:13