我正在构建一个简单的计算器,该计算器将两个数字相加并在另一个框中显示结果。我已经弄清楚了如何从一个框中复制文本并在另一个框中显示它,但是我仍然坚持如何清除它。原始文本框中的数据将清除,但显示框中文本框中的数据将清除。以下是html,css和js文件的代码。
function startOver() {
document.demo_form.txt1.value="";
document.demo_form.txt2.value="";
document.demo_info.txtresult.value="";
document.getElementById("demo_info").innerHTML="";
}
function copy() {
var txt1 = document.getElementById("txt1");
var field1 = document.getElementById("field1");
field1.value=txt1.value;
var txt2 = document.getElementById("txt2");
var field2 = document.getElementById("field2");
field2.value=txt2.value;
}
function calculate(){
var q=parseInt(document.getElementById("txt1").value);
var w=parseInt(document.getElementById("txt2").value);
var result=q+w;
if(isNaN(q)||isNaN(w)){
alert("please enter a number");
}
else
{
var result=q+w;
document.getElementById("txtresult").value=result;
}
}
#container {
width:650px;
height:450px;
margin:0px auto;
padding:10px;
background-color:white;
border:1px solid black;
}
#demo_src {
float: left;
width: 250px;
height: 220px;
margin-bottom: 10px;
border: 1px solid blue;
}
#demo_info {
float: right;
width: 350px;
height: 220px;
margin-bottom: 10px;
border: 1px solid orange;
}
#table_header {
clear: both;
width: 649px;
height: 50px;
border: 1px solid black;
}
#table {
overflow: auto;
width: 649px;
height: 20px;
border: 1px solid black;
}
#table {
align: center;
font-family: Sans-serif;
font-size: 13px;
}
<div id="container">
<h2>Simple Calculator</h2>
<div id="demo_src">
<form name="demo_form">
<table style=margin:10px;>
<tr>
<td>Enter the First Number:</td>
<td><input type = "text" name="txt1" id="txt1" size = "10"/></td>
</tr>
<tr>
<td>Enter the Second Number:</td>
<td><input type = "text" name="txt2" id="txt2" size = "10"/></td>
</tr>
<td><input type="button" value="Add" onclick="calculate();
copy()"/></td>
<td><input type = "button" onclick = "startOver()"
value = "Start Over"/></td>
</table>
</form>
</div>
<div id = "demo_info">
<table style=margin:10px;>
<tr>
<td>Field 1:</td>
<td><input type="text" name="field1" id="field1" size="15"/></td>
</tr>
<tr>
<td>Field 2:</td>
<td><input type = "text" name="field2" id="field2" size = "15"/></td>
</tr>
<tr>
<td>Result: </td>
<td><input type="text" id="txtresult" size="10"></td>
</tr>
</table>
</div>
</div>
</body>
</html>
最佳答案
在FORM及其子项INPUT中,仅按名称即可按点获取子项元素是可以的,但在其他HTML元素中,不适用于Parent和deep Children。您可以直接通过ID获取该元素:
document.getElementById("txtresult").value="";
关于javascript - 如何删除或清除已复制到其他文本框中的数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37913026/