I have 5 checkboxes in class check(named cb1, cb2, cb3, …) and 5 corresponding textfields in class text(named tf1, tf2, tf3, …). When one or more checkboxes are checked I want to count all checked checkboxes and place the sum into the textfields that correspond when a button is clicked.
Example: If cb1 and cb3 are checked than tf1 and tf3 will have value 2.
So far I am counting total checked checkboxes like so:
$(':button').click(function() {
total= $('.check:checked');
count=total.length;
});
But I can’t figure out how to get ‘count’ in the corresponding textfields. Any help is appreciated!
P.S. I have different checkboxes and textfields in different classes so it is important they are referenced by class.
Perhaps a little something like this:
Each element with class
textwill be updated to have a value of eithercountor0depending on whether its corresponding checkbox is checked. Obviously if you’d prefer you can blank out the fields corresponding to unchecked checkboxes by replacing0with''(empty string).(For more information on passing a function to the
.val()method, read the doco.)Note that you should always declare your variables with
varor you create globals.Working demo: http://jsfiddle.net/aBSNy/