I have a simple function:
var total = 0.00;
$("#basket .txt").each(function() {
total += parseFloat($(this).html());
});
$('#total').text('Total: ' + total.toFixed(2));
That is used in 3 places on a script. How do I turn it into a function that can be called in the relevant places a bit like:
getTotal();
rather than use the "first" code above in each of the 3 places.
Thanks in advance
jigfox
18.2k3 gold badges62 silver badges74 bronze badges
asked Jun 30, 2010 at 11:13
user351657
3612 gold badges8 silver badges18 bronze badges
-
20.00 is unnecessary in javascript, because the language is loosely typed. Just say 0.gblazex– gblazex2010年06月30日 11:20:01 +00:00Commented Jun 30, 2010 at 11:20
1 Answer 1
as simple as that:
function getTotal() {
var total = 0.00;
$("#basket .txt").each(function() {
total += parseFloat($(this).html());
});
$('#total').text('Total: ' + total.toFixed(2));
}
answered Jun 30, 2010 at 11:18
jigfox
18.2k3 gold badges62 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
cusspvz
please, edit "getTotol" to "getTotal", and remove ".00" from "var total = 0.00; "... +1
Nick Craver
+1 - (Psst Totol isn't a word ;) I would add make sure not to do this:
$(selector).event(function() { getTotal(); }); like I see so often, $(selector).event(getTotal); is all you ever need.user351657
Hi Jens, thanks, but I tried "that" before posting and the rest of the script breaks yet run the code "inside" the other functions and it works perfectly
lang-js