gpt4 book ai didi

javascript - 当选中复选框时,如何在金额值之前显示美元符号?

转载 作者:行者123 更新时间:2023-11-28 19:45:04 25 4
gpt4 key购买 nike

如果未选中该复选框,它将显示 $0.00

当我选中该复选框时,它将显示1.00。我希望它显示 $1.00。我怎样才能做到这一点?

Demo on JS Fiddle

这是代码:

<form id="form1" method="post">
<input type="text" id="totalcost" value="$0.00">
<input type="checkbox" value="aa_1">
<input type="checkbox" value="aa_2">
<input type="checkbox" value="aa_3">
</form>


<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {

var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum += parseFloat(pay_out_value); // 9.99


} else {
if (thisInput.type.toLowerCase() === 'checkbox') {

var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum -= parseFloat(pay_out_value); // 9.99


}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
}
}
return null;
}());
</script>

最佳答案

只需更改此行:

totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";

totalcost.value = (sum > 0) ? "$" + sum.toFixed(2) : "$0.00";
^

这将在您的价格前添加 $!

FIDDLE

关于javascript - 当选中复选框时,如何在金额值之前显示美元符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433210/

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