views:

30

answers:

1

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

+3  A: 

as simple as that:

function getTotal() {
  var total = 0.00;
  $("#basket .txt").each(function() {
    total  += parseFloat($(this).html());
  });
  $('#total').text('Total: ' + total.toFixed(2));
}
jigfox
please, edit "getTotol" to "getTotal", and remove ".00" from "var total = 0.00;"... +1
CuSS
+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.
Nick Craver
@Cuss: Thanks, done!
jigfox
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
OOPS got it had deleted a } durrr .... thanks
@Nick: s/event/each :)
jAndy