我有一个输入文本,用于显示计算结果:
<input type="text" id="total" readonly/>
总数填充到js文件中的函数内,如下所示:
//Inside a .js file
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
而且我还有一个重置按钮,用于重置表单,但不重置只读输入文本:
<input type="reset" value="Reset"/>
我尝试将重置为按钮,并编写了禁用只读功能,重置然后启用只读功能,但它也无法正常工作:
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
//Inside .js file
function resetForm(formName){
document.getElementById("total").readonly = false;
document.forms[formName].reset();
document.getElementById("total").readonly = true;
}
有人知道这种情况的解决方法吗?我是javascript的新手,我这样做只是出于学习目的。
这是完整的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="allJsCodesHere.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1> <strong>CDs Purchase Order</strong></h1>
<form name="ex2Form" action = "">
<table>
<thead>
<tr>
<th>
Number of CDs ordered:
</th>
<td>
<input type="text" id="amount" value="0"/>
</td>
<td>
<input type="button" value="Calculate" onclick="calculate();"/>
</td>
</tr>
</thead>
<tbody>
<td colspan="3">
At the rate of AED 45 for each CD
</td>
</tbody>
<tfoot>
<tr>
<th>
Total Order:
</th>
<td>
<input type="text" id="total" readonly/>
</td>
<td>
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
</td>
</tr>
</tfoot>
</table>
</form>
<footer>
<p>Created by Mir Adnan Siraj</p>
</footer>
</body>
</html>
计算功能:
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
Document.forms返回特定页面内所有表单的集合。写作document.forms["myForm"]
将返回带有该"myForm"
集合名称的表格。因此,您需要做的就是这个。假设您的表单名称是myForm,其ID为myForm。
<form id="myForm" name="myForm">
<input id="email" name="email" value="[email protected]" />
</form>
现在要访问此表单,您必须执行此操作。
document.forms["myForm"].reset()
这将成功重置您的表单。因此,很明显,您只是在console.log并检查传递的参数即可完美地完成所有工作。您无需通过为它们分配空字符串来手动重置所有字段。错了!
//Inside .js file
function resetForm(formName){ //==========> this needs to return the form name. console.log and check if its returning the formname
document.getElementById("total").readonly = false;
document.forms['formName'].reset();
document.getElementById("total").readonly = true;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句