gpt4 book ai didi

javascript - 如何在 HTML 中使用 INPUT 中的数据并将其应用于 Javascript 中的变量

转载 作者:行者123 更新时间:2023-12-03 13:17:20 25 4
gpt4 key购买 nike

我正在尝试制作一个基本的钱包程序,将我的当前值(value)列在顶部。无论在表格中输入什么数字,然后都会提交,希望然后将总数重新调整为新的金额。相当简单,我觉得我很接近,但我就是不知道缺少什么。

它似乎没有从第一个输入中获取数据并通过函数运行它,也许我需要一个 Action ?我已经尝试过行动,甚至使用新的 currentCash 但它不起作用......真的可以使用一些帮助。非常感谢!

     <html>
<head>
<title>My Wallet</title>
<script type="text/javascript">
currentCash = 40000;

function deductFromTotal(){

var spent = document.getElementById("money_spent");
currentCash -= spent;
return currentCash; }
</script>
</head>

<body>
<h2>Current total is: <script type="text/javascript">
document.write(currentCash);
</script> </h2>

<input type="amount" size= 25 Placeholder="How much did you spend today?" ID="money_spent" >
<input type="button" value= "confirm" onClick="deductFromTotal()">

</body>
</html>

最佳答案

I have modified your question and tried to solve your issue.Hope it helps

  1. You were not taking the input's value

  2. You are using document.write ,you should select the element and change the text content

  3. You should use let ,var or const statements to declare your variables (A good practice to adopt)


您还应该检查输入的值是否为数字,否则返回 NaN

let currentCash = 40000;

function deductFromTotal() {
var spent = document.getElementById("money_spent").value;
// check if the entered value is number
if (isNaN(Number(spent))) {
console.log("Numbers only")

} else {

//currentCash = currentCash - spent;
currentCash -= spent;
// give your h2 an id and then use getElementById ,better
document.querySelector("h2").textContent = `Current total is:${currentCash}`;

}
}
// deductFromTotal();
<html>

<head>
<title>My Wallet</title>
</head>

<body>
<input type="amount" size=2 5 Placeholder="How much did you spend today?" id="money_spent">
<input type="button" value="confirm" onClick="deductFromTotal()">
<h2>Current total is:
</h2>
</body>

</html>

关于javascript - 如何在 HTML 中使用 INPUT 中的数据并将其应用于 Javascript 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com