Sum values of checkbox labels

678 views Asked by At

I've got checkboxes with labels like 1 some text I would like to get the number out of the labels of the checkboxes that are checked and add them together. I was trying to do something like what I have below but it is not giving me anything.

var total = 0;

$('input:checked').each(function () {
    total += parseInt($("label[for='" + this.id + "']").text());
});

Here is an example checkbox

<label><input type="checkbox" id="enbapicks-1" name="ENBApicks[1]" value="1" checked> 1 Golden State</label>
<label><input type="checkbox" id="enbapicks-5" name="ENBApicks[5]" value="1" checked> 5 Memphis</label>
2

There are 2 answers

3
Leo On BEST ANSWER

Your label doesn't have for attribute, that's why $("label[for='" + this.id + "']") returns blank, and thus .text() returns empty string.

You should specify it like this:

<input type="checkbox" id="enbapicks-1" name="ENBApicks[1]" value="1" checked>
<label for="enbapicks-1">1 Golden State</label>

If you can't change HTML, you could get the label from input with parent() method:

<label><input type="checkbox" value="1" checked>1 Golden State</label>

$('input').parent().text() // "1 Golden State"

Alternatively you could set the number as input's value attribute, then use val() method to grab it from input elements.

<input type="checkbox" value="3">

$('input').val() // "3"

As long as you could, always specify for attribute for meaningful label elements.

0
Jon P On

As I mentioned in a comment. You should store the data somewhere more logical. One option would be the value for the check box the other is as a data attribute as demonstrated below

$(document).ready(function(){
//Set a handler to catch clicking the check box
  $("#boxes input[type='checkbox']").click(function(){
    var total=0;
    //lOOP THROUGH CHECKED
    $("#boxes input[type='checkbox']:checked").each(function(){
         //Update total
          total += parseInt($(this).data("exval"),10);
    });
    $("#result").text(total);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="boxes">
<label><input type="checkbox" id="enbapicks-1" name="ENBApicks[1]" value="1" data-exval="1"> 1 Golden State</label>
<label><input type="checkbox" id="enbapicks-5" name="ENBApicks[5]" value="1" data-exval="5"> 5 Memphis</label>
<label><input type="checkbox" id="enbapicks-7" name="ENBApicks[7]" value="1" data-exval="7"> 7 Who Knows</label>
  </div>
<div>Result: <span id="result"></span></div>