views:

222

answers:

3

I'm trying to update a Total: (span.wrap p span) field at the bottom of a form using jQuery.

I have a few checkboxes, each of which has an associated price contained within the title attribute like so: title="$2".

I'd the Total: field to update dynamically when the user clicks a checkbox. Here is the script I have, but it's throwing a syntax error as shown.

$("input:checkbox").toggle(
  var v = $(this).attr("title").substr(-1) * 1; // syntax error here. subtstr() eliminates the $ sign
  var t = $("span.wrap p span").text() * 1; // converts the string to a number
  function () {
   $("span.wrap p span").text(t + v);
  },
  function () {
   $("span.wrap p span").text(t - v);
  }
 );

Note: The total field has an initial value of 0. There are four checkboxes; perhaps I need to use each()?

Any ideas on how to make this work?

+1  A: 

Toggle accepts a function

$("input:checkbox").toggle(function() {
   var v...
David Hedlund
A: 

change:

var v = $(this).attr("title").substr(-1) * 1

to

var v = $(this).attr("title").substr(1) * 1
TheVillageIdiot
also wrap it into a function block as suggested by d.
TheVillageIdiot
+1  A: 

When you use a toggle function, afaik you can only define code within the two function blocks.

Psytronic