I need the script for averaging checkbox values (CSS class = checkbox) with the result being placed in a field with CSS class = checkboxaverage. The number of checkbox values will differ.
Question
Question
Answer
Make sure your checkbox choices have corresponding numerical values. Then you can use javascript like
$(document).ready(function () { $('.checkbox').change(function () { var sum = 0; var count = 0; $('.checkbox input:checked').each(function(){ sum += Number($(this).val().replace(/V_/g,'')); count += 1; }); $('.checkboxaverage input').val((sum/count).toFixed(2)); }); });
Replies
Hi there,
Can you show me a screenshot what's the real world use case?
I want to take evaluation ratings selected using a checkbox that have assigned values and have a field that shows the average rating (per category). I was able to use a script to add all of the checkbox values to show an overall total score, but need an average. The number of categories will vary.
I used this and it worked: thank you!
$(function() {
$(".checkbox").change(function () {
var sum = 0
var inputTotal = 0
var average = 0
$(".checkbox input:checked").each(function(){
sum += Number($(this).val().replace(/V_/g,''));
inputTotal++;
});
$(".checkboxsum input").val(sum);
average=sum /inputTotal;
$(".checkboxaverage input").val(average);
});
});