1 回答
TA贡献1779条经验 获得超6个赞
两件事:
-首先,找出在单击按钮和按 Enter 键时运行的通用代码,然后将其放入单个函数中,
-其次,请注意,您的输入将始终是一个字符串,您必须将parseInt
其输入求和
这是一个工作示例:
<div id="myForm">
<input type="text" id="bedrag" />
<button type="button" onclick="check_field('bedrag');" value=''>Enter</button>
<p>Uw totaal:</p>
<p id="resultaat"></p>
</div>
<script>
var totaal = 0;
var bedrag = document.getElementById("bedrag");
bedrag.onkeydown = bereken
function submit() {
var ingevoerdeBedrag = document.getElementById("bedrag").value;
if (isNaN(parseInt(ingevoerdeBedrag))) {
alert('not a number');
} else {
totaal = totaal + parseInt(ingevoerdeBedrag);
document.getElementById("resultaat").innerHTML = 'Het bedrag is ' + totaal;
}
}
function bereken(e) {
if (e.keyCode == 13) {
submit();
}
}
function check_field(id) {
submit();
// Here we're clearing the input only after clicking the button
document.getElementById(id).value = "";
}
</script>
添加回答
举报