jquery - How can I get an input text to expand its digits to two if the user only enters one? -
i want display values in text inputs in "dollar format"; iow, instead of "10.5" want "10.50"
i able in grand total box (last line of code):
$(document).on("blur", '.amountbox', function (e) { var amount1 = $('[id$=boxamount1]').val() != '' ? parsefloat($('[id$=boxamount1]').val()) : 0; var amount2 = $('[id$=boxamount2]').val() != '' ? parsefloat($('[id$=boxamount2]').val()) : 0; var amount3 = $('[id$=boxamount3]').val() != '' ? parsefloat($('[id$=boxamount3]').val()) : 0; var amount4 = $('[id$=boxamount4]').val() != '' ? parsefloat($('[id$=boxamount4]').val()) : 0; var amount5 = $('[id$=boxamount5]').val() != '' ? parsefloat($('[id$=boxamount5]').val()) : 0; var grandtotal = amount1 + amount2 + amount3 + amount4 + amount5; $('[id$=boxgrandtotal]').val(parsefloat(grandtotal).tofixed(2)); });
that working, thought maybe individual "amount" boxes work doing (adding ".tofixed(2)" val()s):
var amount1 = $('[id$=boxamount1]').val() != '' ? parsefloat($('[id$=boxamount1]').val().tofixed(2)) : 0; var amount2 = $('[id$=boxamount2]').val() != '' ? parsefloat($('[id$=boxamount2]').val().tofixed(2)) : 0; . . .
it didn't; fact, broke existing functionality.
so "dialed bit" , tried on first "amount" box so:
$('[id$=boxamount1]').val() == parsefloat($('[id$=boxamount1]').val().tofixed(2));
...but failed (entering "10.5" , exiting/blurring did not convert "10.5" "10.50" hoped).
how can cause inputs expand or contract display 2 digits? iow:
"10" should become "10.00" "10.5" should become "10.50" "10.567" should become "10.57"
etc.
instead of this:
$('[id$=boxamount1]').val() == parsefloat($('[id$=boxamount1]').val().tofixed(2));
… this:
$('[id$=boxamount1]').val(parsefloat($('[id$=boxamount1]').val()).tofixed(2));
note tofixed()
method works numbers only, need apply numeric result of parsefloat()
instead of string result of val()
.
entire code can reduced following:
$(document).on('blur', '.amountbox', function() { var grandtotal = 0; $('.amountbox').each(function() { var v= +$(this).val(); if(v>'') { $(this).val(v.tofixed(2)); grandtotal+= v; } }); $('#boxgrandtotal').val(grandtotal.tofixed(2)); });
the jquery each
method saves trouble of looking @ each input individually.
prepending plus sign (+) string coerces number, parsefloat
isn't needed.
Comments
Post a Comment