Javascript 按下时';输入';,对输入求和并清除它
我正在开始学习JS。我正在尝试创建一个用户可以在文本字段中输入数字的页面。用户可以按enter键添加其他号码。当用户按下enter键时,需要清除输入字段 输入的金额必须加在一起,并且其总额必须显示在第二个文本框中 我的HTML:Javascript 按下时';输入';,对输入求和并清除它,javascript,Javascript,我正在开始学习JS。我正在尝试创建一个用户可以在文本字段中输入数字的页面。用户可以按enter键添加其他号码。当用户按下enter键时,需要清除输入字段 输入的金额必须加在一起,并且其总额必须显示在第二个文本框中 我的HTML: <input type="text" id="input"> <p>Uw totaal:</p> <input type="text" id="output"> 每个浏览器都可以使用按键。问题是我不能对这些数字求和。如果
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
每个浏览器都可以使用按键。问题是我不能对这些数字求和。如果我把它放在按键功能中,每当你再次按回车键时,这个数字就会被清除
我希望你们能帮忙 在清除之前获取值
var input=document.getElementById(“输入”);
var output=document.getElementById(“输出”);
var合计=0;
input.onkeypress=功能(e){
如果(e.keyCode==13 | | e.key==13){
总+=+输入值;
产值=总产值;
input.value=“”;
}
};代码>
Uw totaal:
试一试-
var总计=0;
输入=document.getElementById(“输入”);
输出=document.getElementById(“输出”);
input.onkeypress=功能(e){
总计=总计+输入值*1;
如果(e.keyCode==13){
input.value=“”;
}
产值=总产值;
};代码>
Uw totaal:
您过早地清除了输入字段
var number = 0
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
number += input.value;
input.value = "";
}
return number;
}
document.getElementById("output").value = number;
请注意,number
变量不能在checkKey函数中声明。问候语您正在更新ceckKey函数外部的输出元素
此更新不是自动的。你必须触发它。
此外,请仔细检查该功能。回调可以返回一个值,但是使用dame函数进行回调并获取输出内容看起来不太好。在计算总数之前,您正在清除输入值。我已经更新了您的代码,使其能够按照您的预期工作
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
checkKey(event);
};
function checkKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
// Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
outputValue = (output.value == '') ? 0 : output.value;
total = parseInt(outputValue) + parseInt(input.value);
input.value = "";
// To update the total in output text box
document.getElementById("output").value = total;
}
}
顺便说一句,您可能想命名函数checkKey()
:)
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
checkKey(event);
};
function checkKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
// Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
outputValue = (output.value == '') ? 0 : output.value;
total = parseInt(outputValue) + parseInt(input.value);
input.value = "";
// To update the total in output text box
document.getElementById("output").value = total;
}
}