0

I have a list of checkboxes when I check them I get the value and then I want to add them up but I can't seem to get me head around it.

example http://jsfiddle.net/zidski/w3mwkkh3/

$('body').on('click' , '.done' , function() {
            var selectedCheckboxValue = "";
            $('input.checkbox:checked').each(function() { 


                selectedCheckboxValue +=  $(this).val(); 

          });

          $('.filter-selected-count').text(selectedCheckboxValue);

        });
0

2 Answers 2

5

You should replace your code to this

var selectedCheckboxValue = 0;
$('input.checkbox:checked').each(function() { 
   selectedCheckboxValue += parseInt($(this).val()); 
});

See here this works fine

Demo

Sign up to request clarification or add additional context in comments.

Comments

3

To sum the values of selected checkboxes you can get the values but first convert them to integer like:

$('body').on('click', '.done', function() {
  //declare a variable to sum the values of checked checkboxes
  var sum = 0;
  $('input.checkbox:checked').each(function() {
    //you can first convert to int before sum them
    sum += ~~$(this).val();

  });
  //add the result
  $('.filter-selected-count').text(sum);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <label>
      <input id="checkbox1" class="checkbox" type="checkbox" name="rooms" value="2" />Rooms (2)</label>
  </li>
  <li>
    <label>
      <input class="checkbox" type="checkbox" name="bathroom" value="2" />Bathroom (2)</label>
  </li>
  <li>
    <label>
      <input class="checkbox" type="checkbox" name="view" value="2" />View from room (2)</label>
  </li>
  <li>
    <label>
      <input class="checkbox" type="checkbox" name="dining" value="2" />Dining (2)</label>
  </li>
  <li>
    <label>
      <input class="checkbox" type="checkbox" name="grounds" value="2" />Hotel &amp; grounds (2)</label>
  </li>
  <li>
    <label>
      <input class="checkbox" type="checkbox" name="localarea" value="2" />Local area (2)</label>
  </li>
</ul>
<button class="done">Done</button>
<br />Count: <span class="filter-selected-count"></span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.