【问题标题】:How to add numbers value in ONE input text?如何在一个输入文本中添加数字值?
【发布时间】:2021-11-19 05:47:41
【问题描述】:
我已经编码并使用了 for 循环,但只有在我使用多个输入文本时才有效。
我想实现:
每次我在一个输入文本上输入数字并点击“加”或“减”按钮时,我希望下面的总数在加减时不断更新。
let total = 0;
for(var i=0; i<priceTrim.length; i++){
if(parseInt(priceTrim[i].value))
total += parseInt(priceTrim[i].value);
}
document.getElementById('total').value = total;
请看截图
【问题讨论】:
标签:
javascript
operator-keyword
tracker
【解决方案1】:
据我了解,您想输入商品的名称和价格,然后通过加减按钮进行加减操作。另外,您还想管理总价值。
我通过您的屏幕截图创建了一个程序。代码写在下面。
// Selecting the Elements from Html
Item_Name = document.getElementById("Item_Name");
var Price = document.getElementById("Price");
var Add = document.getElementById("Add");
var Deduct = document.getElementById("Deduct");
var Name_Here = document.getElementById("name_here");
var Price_Here = document.getElementById("price_here");
var Total = document.getElementById("Total");
var Total_Value = 0;
// Get and Set the values
Add.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value += parseInt(Price.value);
Total.innerText = Total_Value;
}
Deduct.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value -= parseInt(Price.value);
Total.innerText = Total_Value;
}
.flex_container{
display: flex;
justify-content: center;
}
.container{
width: 300px;
min-height: 220px;
border: 1px solid black;
padding: 10px;
}
button{
margin: 12px 0px;
}
.Span_Header{
display: flex;
justify-content: space-between;
}
input{
width: 100%;
margin: 8px 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="flex_container">
<div class="container">
<span>Item name</span><br>
<input type="text" name="item_name" id="Item_Name" placeholder="Item name"><br>
<span>Price</span><br>
<input type="number" name="price" id="Price" placeholder="Price"><br>
<button id="Add">Add</button>
<button id="Deduct">Deduct</button>
<div class="Span_Header">
<span>Item name</span>
<span>Price</span>
</div>
<hr>
<div class="Span_Header">
<span id="name_here">Name Here</span>
<span id="price_here">Price Here</span>
</div>
<hr>
<div class="Total_div">
<span>Total: </span>
<span id="Total"></span>
</div>
</div>
</div>
</body>
</html>
【解决方案2】:
如果您想要答案,请提供您的所有代码。什么是 priceTrim?
您是否尝试遍历多个文本框值?如果是这样,您将不得不使用 querySelectorAll domElement 方法进行循环,因为它返回所有文本框的数组类型,然后您可以在函数中指定要对这些信息执行的操作。
你的 if 语句语法也是错误的。如果您的测试条件返回 true,则没有代码块可供代码执行。
请输入所有代码并尝试解释您想要实现的具体目标是什么?我觉得你讲了一半!