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

时间:2014-06-26 14:29:46

标签: javascript

如果未选中该复选框,则会显示$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>

2 个答案:

答案 0 :(得分:2)

只需更改此行:

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

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

这会在你的价格之前加上$!

FIDDLE

答案 1 :(得分:1)

只需将$附加到值:

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

Fiddle