HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Writing a checkbox with jQuery

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withwritingjquerycheckbox

Problem

If a checkbox is clicked, it will be added to the total, if not, it will be deducted or ignored. (The total number of checkboxes I have in real is 25.)

Is there a way to write the code below in a shorter version?

Function

function tblcheckboxes(){
    var a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, total;
    if ($('#tcbx1').is(":checked")) {
         a = parseFloat($("#tcbx1").val(), 10);
    }
    if ($('#tcbx2').is(":checked")) {
         b = parseFloat($("#tcbx2").val(), 10);
    }
    if ($('#tcbx3').is(":checked")) {
         c = parseFloat($("#tcbx3").val(), 10);
    }
    if ($('#tcbx4').is(":checked")) {
         d = parseFloat($("#tcbx4").val(), 10);
    }
    if ($('#tcbx5').is(":checked")) {
         e = parseFloat($("#tcbx5").val(), 10);
    }


jQuery

$(document).ready(function(){
    $('#tcbx1').click(function(){
            tblcheckboxes();
    });
    $('#tcbx2').click(function(){
            tblcheckboxes();
    });
    $('#tcbx3').click(function(){
            tblcheckboxes();
    });
    $('#tcbx4').click(function(){
            tblcheckboxes();
    });
    $('#tcbx5').click(function(){
            tblcheckboxes();
    });
   });

Solution

Why not do something like this:

$(document).ready(function() {
     $('.containerClass-filter-expression-that-selects-all-your-chks').click(function() {
       recalculate();
     });
});

function recalculate(){
   $('.some-expression-that-selects-all-your-checkboxes').each(function() {
       if($(this).is('checked')) {
           //add

       } else {
           //substract from total
       }

   });
};

Code Snippets

$(document).ready(function() {
     $('.containerClass-filter-expression-that-selects-all-your-chks').click(function() {
       recalculate();
     });
});

function recalculate(){
   $('.some-expression-that-selects-all-your-checkboxes').each(function() {
       if($(this).is('checked')) {
           //add

       } else {
           //substract from total
       }

   });
};

Context

StackExchange Code Review Q#74669, answer score: 2

Revisions (0)

No revisions yet.