Adding checkbox values using Jquery

时间:2019-04-17 02:10:31

标签: jquery

I am trying to add the checkbox values on button click using Jquery. Please help. I want to display the result in the paragraph.

 <div class="container">
 <input type="checkbox" classname="check" id="one" value="1"> 1 <br>
 <input type="checkbox" classname="check" id="two" value="2"> 2 <br>
 <input type="checkbox" classname="check" id="three" value="3"> 3 <br>
 <input type="checkbox" classname="check" id="four" value="4"> 4 <br>
 <input type="checkbox" classname="check" id="five" value="5"> 5 <br>
 <button type="button" id="button"> Add </button><br>
 <p id="total"></p>
 </div>

Clicking on the ADD button the output should be printed below.

Link to Example

2 个答案:

答案 0 :(得分:1)

On button click event below will give you the total of all the checked checkboxes

var total = 0;
          $('input:checkbox:checked').each(function(){ // iterate through each checked element.
            total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
          }); 

Working Example

答案 1 :(得分:0)

Please try this code. here is jsfiddle https://jsfiddle.net/yswme32f/4/

var addButton = document.getElementById("button");
var totalP  = document.getElementById("total");

addButton.onclick = function(){
  var total =0; 
  $.each($("input[classname='check']:checked"), function(){            
    total = total + Number($(this).val());
  });
  totalP.innerText = "total value "+ total;    
}