0

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

1
  • What have you tried so far to do this? Commented Apr 17, 2019 at 2:24

2 Answers 2

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

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

Comments

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

1 Comment

@devi I am glad that it worked for you. Please consider marking my answer :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.