繁体   English   中英

使用javascript onFocus事件在另一个字段中显示表单输入元素的内容

[英]Displaying content of form input element in another field using javascript onFocus event

问题:我希望Javascript计算用户的两个数字输入的总和,并在用户选择或单击该字段后立即在第三个字段中显示总和。 错误:当第三个字段聚焦时,Firefox,Chrome和Safari都显示为零; 但是,为了公平起见,Firefox在刷新后不情愿地显示所需结果; 其他人没有。 我怀疑自己的代码中存在无法识别的错误,请提供帮助。

  window.onload = function() { var input1 = document.getElementById('bk').value; var input2 = document.getElementById('softw').value; input1 = Number(input1); // convert input to number input2 = Number(input2); input3 = input1 + input2; // Sum the inputs document.getElementById('total').onfocus = function() { document.getElementById('total').value = input3; return input3; } } 
 <html> <body> <div id='fm_div'> <form action="#" method="GET" id='form1'> <p>Qty of Books: <input type="text" name="bkqty" id='bk'> </p> <p>Qty of Software: <input type="text" name="software" id='softw'> </p> <p>Total: <input type='text' id='total'> </p> <p> <input type='submit' value='send' id='submit'> </p> </form> </div> </body> </html> 

要设置input1input2的窗口加载功能。 但是文本框不会加载任何值。 如下更改您的window.onload函数

 window.onload = function() { document.getElementById('total').onfocus = function() { var input1 = document.getElementById('bk').value; var input2 = document.getElementById('softw').value; input1 = Number(input1); // convert input to number input2 = Number(input2); input3 = input1 + input2; // Sum the inputs document.getElementById('total').value = input3; return input3; } } 
 <div id='fm_div'> <form action="#" method="GET" id='form1'> <p>Qty of Books: <input type="text" name="bkqty" id='bk'> </p> <p>Qty of Software: <input type="text" name="software" id='softw'> </p> <p>Total: <input type='text' id='total'> </p> <p> <input type='submit' value='send' id='submit'> </p> </form> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM