0

Edit: this isn't a math or operators question (I don't think). This is a formatting or masking question.

Creating an order form. I have Javascript that tallies/totals each column and displays the quantity and column cost in two other fields. I would like for the column cost to be formatted with a decimal and 2 values after it, but can't seem to figure it out. .toFixed(2) doesn't seem to work (because it's a string?) and I'm wondering if it's because the quantity and cost fields are readonly?

I'm stuck.

    //example of tallying one column

    <input type="number" min="0" value="0" name="proA#x#" class="input-mini proA qty1 coffee total">

    $(document).on("change", ".qty1", function() {
        var sum = 0;
        $(".qty1").each(function(){
            sum += +$(this).val();
        });
        $(".total1").val(sum);
        $(".cost1").val(sum*9.00);
    });


    //item tally

    <input type="number" id="D1" name="D1" class="input-mini uneditable-input total1" placeholder="0" readonly>


   //item cost

   <input type="number" id="" name="" class="input-mini uneditable-input cost1" placeholder="x 9.00" readonly >

Thanks in advance!

Big Mike
  • 119
  • 10
  • I'm not sure why this was marked as a duplicate @Barmar. I looked at that other thread - doesn't seem to have anything to do with what I'm asking. Help me to understand. – Big Mike Dec 16 '15 at 21:03
  • I didn't notice the `+` before `$(this).val();`, I thought you were concatenating the values instead of adding them. – Barmar Dec 16 '15 at 21:05
  • 2
    But now I don't understand why `$(".cost1").val((sum*9).toFixed(2))` doesn't work for you. – Barmar Dec 16 '15 at 21:05
  • @BigMike Your code does't show were you are calling `toFixed()` and it doesn't work – Ruan Mendes Dec 16 '15 at 21:07
  • Right. I didn't have the .toFixed() in there. Barmar's formatting solved it. Thanks, guys! – Big Mike Dec 16 '15 at 21:08

1 Answers1

1

I would do it this way

var sum = 0.00;
$(".qty1").each(function(){
     sum += parseFloat($(this).val());
});

$(".cost1").val(sum.toFixed(2));
jpganz18
  • 5,508
  • 17
  • 66
  • 115