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:
$(':button').click(function() {
var total= $('.check:checked'),
count=total.length;
$('.text').val(function() {
return $('#' + this.id.replace(/tf/,'cb')).is(':checked') ? count : 0;
});
});
Each element with class text will be updated to have a value of either count or 0 depending on whether its corresponding checkbox is checked. Obviously if you'd prefer you can blank out the fields corresponding to unchecked checkboxes by replacing 0 with '' (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 var or you create globals.
Working demo: http://jsfiddle.net/aBSNy/
You can do it like this:
HTML:
<div>
<input type="checkbox" name="check1" value="" />
<input type="text" name="text1" value="" data-count-for="check1" />
</div>
...(other checkboxes)...
<div>
<input id="trigger" name="trigger" type="button" value="Click me" />
</div>
JavaScript (using jQuery 1.7+):
jQuery("#trigger").on('click', function(event){
event.preventDefault();
// select checkboxes:
var checkboxes = jQuery(':checkbox:checked');
checkboxes.each(function(){
// find text input assigned to each checked checkbox:
var selector = '[data-count-for="' + jQuery(this).attr('name') + '"]';
// assign it a total number of previously found checkboxes
jQuery(selector).val(checkboxes.length);
});
});
See proof here: http://jsfiddle.net/EMhuw/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With