0

I am using the following code below to get the price from the attribute data-price which is assigned to radio buttons like so: data-price="25.00"

jQuery(document).ready(function($){
var frm = document.forms.myForm;
frm.onchange = function(e) {
var tot = 0;
for( var i = 0, l = frm.elements.length; i < l; i++ ) {
    if( frm.elements[i].checked ) {
        tot += parseFloat( frm.elements[i].getAttribute('data-price') );
    }  
}
document.getElementById('total').value = ( tot );
}
})

The problem I am getting is that when it dispalys it in the input box for the following example it would only show 25 I need it to say 25.00 is there a way around this?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Matt
  • 1,747
  • 8
  • 33
  • 58

3 Answers3

2
tot.toFixed(2)

will give you the result.

And since you use jQuery, you could write more jQuery like code, just an example like below, just a suggestion:

$(function () {
    $('form[name="myForm"]').change(function () {
        var tot = 0;
        $('input:checked', this).each(function () {
            tot += parseFloat($(this).data('price'));
        });
        $('#total').val(tot.toFixed(2));
    });
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

Try assigning tot.toFixed(2). Hope that helps!

sgowd
  • 2,242
  • 22
  • 29
1

Javascript won't show 25.00 if it is a number

console.log(25.00);
alert(25.00)

Both will show 25. It works only if there are non-zero digits after .

console.log(25.03);

So convert it to number for the calculations, and when showing in a text box use .toFixed(2) like others have suggested here.

document.getElementById('total').value = tot.toFixed(2);

toFixed converts it to string.

Diode
  • 24,570
  • 8
  • 40
  • 51