You are viewing limited content. For full access, please sign in.

Question

Question

Javascript for averaging checkbox values

asked on October 27, 2015 Show version history

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.  

0 0

Answer

APPROVED ANSWER
replied on October 27, 2015

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));
  });  
});
2 0

Replies

replied on October 27, 2015

Hi there,

Can you show me a screenshot what's the real world use case?

0 0
replied on October 27, 2015

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.  

0 0
replied on October 27, 2015

Hi there,

If user can only choose one rating, it's better to use Radio Button, because checkbox allow one to select multiple

0 0
replied on October 28, 2015

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);
    });
});

 

 

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.