rtstorm
rtstorm

Reputation: 345

Count checked checkboxes with jQuery

I am trying to count and calculate selected checkboxes. They are by default checked. I have 6 checkboxes and need to display in other field. Basically, when they are all checked in a field I need to show 100% and if I uncheck one box the show 83.4% etc.

I found some jQuery script on this forum but they all user class as a reference point to jQuery script. The problem is that I have same class="flat" in other fields.

Here is my HTML:

<div class="item form-group">
  <input type="checkbox" name="hobbies[]" id="Uvod" value="1" class="flat" checked /> Uvod
  <br />

  <input type="checkbox" name="hobbies[]" id="Ponuda/Prodajni_Pristup" value="1" class="flat" checked /> Ponuda/Prodajni Pristup
  <br />

  <input type="checkbox" name="hobbies[]" id="Alternaticna_ponuda" value="1" class="flat" checked /> Alternaticna ponuda
  <br />

  <input type="checkbox" name="hobbies[]" id="Profesionalizam" value="1" class="flat" checked /> Profesionalizam
  <br />

  <input type="checkbox" name="hobbies[]" id="Motivacija" value="1" class="flat" checked /> Motivacija
  <br />

  <input type="checkbox" name="hobbies[]" id="Dodatan_kriterij" value="1" class="flat" /> <b>Dodatan kriterij</b>
  <br />            

  <select class="flat" name="Dodatni_kriterij_odabir" value="<?php echo $values['Dodatni_kriterij_odabir']?>">
    <option disabled selected hidden=></option>
    <option>MBB</option>
    <option>Cross-sell</option>
    <option>#N/A</option>
  </select> Dodatni kriterij odabir
  <br />              
</div>

This is the field i would like to show result of % checked boxes:

<div class="item form-group">
  <label class="control-label col-md-3 col-sm-3 col-xs-12" for="Score">Score <span class="required">*</span>
  </label>
  <div class="col-md-6 col-sm-6 col-xs-12">
    <input type="text" id="Edit_Score" name="Score" value="0" class="form-control col-md-7 col-xs-12">
  </div>
</div>

Is there any other way to count checkboxes but not using class (maybe input id?)

Upvotes: 1

Views: 4969

Answers (2)

AgeDeO
AgeDeO

Reputation: 3157

An element can have more classes. Use class="flat" for your styling and add another for your jQuery

class="flat" can become class="flat counter" and change your jQuery to count the elements with the counter class.

Upvotes: 0

Dan Crews
Dan Crews

Reputation: 3597

You can select all checkboxes with$('[type=checkbox]') or with $(':checkbox'). You can then look at .attr('checked'). If you want all of the inputs that are for that specific input value, you can use $("input[name='hobbies[]']").

var total = $("input[name='hobbies[]']").length;
var checked = $("input[name='hobbies[]']:checked").length;

var percentage = Math.floor((checked / total) * 100);

Upvotes: 2

Related Questions