0

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
1
  • 2
    0.00 is unnecessary in javascript, because the language is loosely typed. Just say 0. Commented Jun 30, 2010 at 11:20

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

please, edit "getTotol" to "getTotal", and remove ".00" from "var total = 0.00; "... +1
+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.
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.