just eric
just eric

Reputation: 927

Update sum when checkbox checked jquery

Here: http://jsfiddle.net/justeric/AWC4U/4/ checking a box will sum all entries in the textfield column and subtract that sum from 100, then it will place the difference in the corresponding textfield. So if 20 is the sum of all entries in the textfield column, checking a checkbox will result in 80 (100-20) being populated in the corresponding textfield. This feature works correctly but here's my problem:

If I uncheck a checkbox the corresponding textfield should return to a zero value without affecting any other textfields. So in the above example the 80 should return to 0 without changing the 20. Also every additional checkbox that is checked should return the new sum of the textfields, including whatever was populated from the last check, right now, the first calculation just keeps repopulating for each additional checkbox that is checked. So if the sum of the checkboxes is 20 and I check a checkbox 80 is populated in the corresponding textfield and that is correct but if I check another checkbox 80 is populated again but that is wrong now 0 should be populated because 100-20-80 = 0.

EDIT IN:

So to make the textfield corresponding to the checkbox clear without affecting the other fields requires something like:

$('.textfield').val(function() {
    if($('#' + this.id.replace(/textfield/,'checkbox')).is(':unchecked')){
return 0;}

This would affect all unchecked checkboxes but I want it only to work if a checked checkbox changes to unchecked. So the value reverts back to 0 in an intuitive manner without affecting any other textfields associated with an unchecked checkbox

Upvotes: 0

Views: 1033

Answers (1)

lucuma
lucuma

Reputation: 18339

Assuming you have a class on the checkboxes you can do something like the following:

$('.checkbox').not(':checked');

So in the change or click handler you could do:

$('.checkbox').click(function() {
   if ($(this).not(':checked')) {
     // it is unchecked so do your uncheck function
     doUncheckSumFunction();  // you'd define this do what you need it to do

     } 
});

You could also define an uncheck function like this:

$('table').on('unchecked', '.checkboxes', function() {
// do the code you want done
});

Then in the first example instead of doUnCheckSumFunction() you can now do:

$(this).trigger('unchecked');

Update:

To loop over a set of elements and do something you can do this:

var $textareas = $('.textclass');

var sum = 0;
$('.checkbox').each(function(i) {
   if ($(this).not(':checked')) {
     sum = sum + 1;
     // or
     $textareas[i].val(0); //etc
   }
});

etc.

Upvotes: 1

Related Questions