1

Hi everyone this is my first time using this site please bear with me because I have no experience in javascript coding. I have the following in my javascript file:

$(document).ready(function() {
$("input").click(function(event) {
    updateTotal();

});
});

function updateTotal() {
var total = 13600;
$("#menu input:checked").each(function() {
    total += parseFloat(this.value);
});
$('#TotalCost').val("$" + total.toFixed(2));
}

And in my source code I have:

            <div class= "checkbox" style="margin-top: 20px" id= "menu">

                Cost of Dinner
                <p>
                    <input type="checkbox" value="-200.00" name="Hamburger">Hamburger ($2)<br/>
                    <input type="checkbox" value="-400" name="French Fries">French Fries ($1)<br/>
                    <input type="checkbox" value="-1.5" name="Shake">Shake ($3)<br/> 
                </p>

            <p>
                Total Cost: <input type="text" name="TotlCost" id="TotalCost"     size="10"/>
            </p>

<div>

How do I format so the updateTotal() will return a number that has commas? I found this code online that formats a string with commas

function commas(str) {
    return str.replace(/.(?=(?:.{3})+$)/g, '$&,');
}

How do I use it? Thank you very much for your help.

4

1 回答 1

0

尝试将该函数添加到您的 JavaScript 文件中,然后将您的代码更改为:

function updateTotal() {
    var total = 13600;
    $("#menu input:checked").each(function() {
        total += parseFloat(this.value);
    });
    var val = commas(total.toFixed(2).toString());
    $('#TotalCost').val("$" + val);
 }

val用逗号设置为总数。

于 2013-10-23T01:14:58.733 回答