gpt4 book ai didi

javascript - 取消选中表单元素时如何减去javascript变量的值

转载 作者:行者123 更新时间:2023-11-28 00:17:35 34 4
gpt4 key购买 nike

请注意,这不是我的代码,也不是表单中的实际代码。这只是我的测试版本,但确实代表了我想要做的事情。

给定以下代码,如何让脚本在取消选中复选框时减去传递的值:

<!DOCTYPE html>
<html lang="en">

<head>
<title>form test</title>
<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
function updateAmount(amount) {
parseInt(amount);
if ($('#amount').val()) {
parseInt(amount);
amount = amount + parseInt($('#amount').val());
}
$('#amount').val(amount);
alert('Amount: ' + $('#amount').val());
}
</script>
</head>

<body>
<form action="" method="post" name="form-test">
<input onclick="updateAmount(150)" class="inputbox" id="reservationfee0"
value="Registration Fee" type="checkbox" />
<strong>$150</strong>Reservation Fee</form>
</body>

</html>

就目前而言,编写函数代码的人没有考虑到人们在提交表单之前可能会选中和取消选中该框(其中包括更多字段和其他在提交之前添加到 amount 变量中的数字)。由于这个原因,有一些关于超额收费的报告,所以我需要弄清楚如何阻止它发生,但我对 javascript/jquery 知之甚少。

最佳答案

尝试:

function updateAmount(amount) {
$amount = $('#amount'); // cache for later use
if ($('#reservationfee0').is(':checked')) {
$amount.val(parseInt($amount.val(), 10) + amount);
} else {
$amount.val(parseInt($amount.val(), 10) - amount);
}
}​

Working example here

这检查是否使用 .is() 检查了 checkbox如果是,则将金额添加到当前值(如果未减去)。

另请注意,parseInt 采用第二个参数 - radix,建议您包含此值以确保结果... docs for parseInt here

关于javascript - 取消选中表单元素时如何减去javascript变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11192862/

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