javascript - 使用 Javascript 从 HTML 表单添加数字,无需提交或刷新
问题描述
您好我正在尝试使用 HTML 创建一个表单,其中用户可以在表单 1 和表单 2 中插入数字。一旦 2 个表单填充了数字,总数会自动显示在下一行,没有提交按钮。
请注意,表单是 Django Forms
这是我尝试过的。
var item_1_amount = document.getElementById("item_1_amount");
var item_2_amount = document.getElementById("item_2_amount");
var total = item_1_amount.value + item_2_amount.value
item_1_amount.onkeyup = function () {
document.getElementById("Total").innerHTML = total.value;
};
<tr>
<td><h6 style="float:left; margin-right:5px; margin-top:7px">$</h6>
<input
autocomplete="off"
type="number"
class="form-control w-25"
name="item_1_amount"
id="item_1_amount"
style="float:left"/>
</td>
<td><h6 style="float:left; margin-right:5px; margin-top:7px">$</h6>
<input
autocomplete="off"
type="number"
class="form-control w-25"
name="item_2_amount"
id="item_2_amount"
style="float:left"/>
</td>
</tr>
<tr>
<th>Total</th>
<th id="Total">$$</th>
</tr>
解决方案
为确保仅在两个输入元素都有值时执行计算,您可以使用对象文字(或其他)跟踪输入元素的值 - 当事件处理程序注册更改时分配值。
/* shorthand utility functions */
const q=(e,n=document)=>n.querySelector(e);
const qa=(e,n=document)=>n.querySelectorAll(e);
/*
Store values from input elements in this object.
When this contains exactly 2 items perform the calculations.
*/
const results={};
qa('[type="number"].form-control').forEach(input=>input.addEventListener('keyup',function(e){
/* add the value against the id to the object described above */
results[ this.name ]=Number( this.value );
/* perfrom calculations on stored values ~ use array.reduce() to generate the SUM */
if( Object.keys( results ).length==2 ){
q('th#total').textContent=[ ...Object.values( results ) ].reduce((a,v)=>a+v);
}
}));
#total:before,
label:before{content:'$'}
label{
display:inline-block;
}
<table>
<tr>
<td>
<label>
<input autocomplete="off" type="number" class="form-control w-25" name="item_1_amount" />
</label>
</td>
<td>
<label>
<input autocomplete="off" type="number" class="form-control w-25" name="item_2_amount" />
</label>
</td>
</tr>
<tr>
<th>Total</th>
<th id="total"></th>
</tr>
</table>
推荐阅读
- javascript - 如何转换数组中已经在javascript中的嵌套对象中的对象
- openlayers - 如何在 Chrome 中获取示例的源映射
- php - 在 PHP 中转换包含表情符号的请求输入并保存在 MySQL 中
- bash - 如何使用 sed 正则表达式模式匹配
- java - 从具有不同布局的 Activity 访问布局的 TextView
- php - rsa 签名验证使用 phpseclib vs openssl
- python - 获取html动态内容python3
- android - 无法将所选项目从微调器保存到数据库
- javascript - 使用变量Javascript动态更改gridTemplateColumns的重复值的任何方法
- php - 使用 php pdo 不为空时触发默认的 mysql 日期时间值