3

I need a function that can add checkbox values on click event. My html code is

<div data-role="fieldcontain">

        <fieldset data-role="controlgroup">

        <center><b> Plattforms </b></center>

        <input type="checkbox" name="cbs" id="cbs" value = 945345  />
        <label for="cbs">945345 Symbian</label>

        <input type="checkbox" name="cbi" id="cbi" value = 945345 />
        <label for="cbi">945345 iPhone</label>

        <input type="checkbox" name="cbb" id="cbb" value = 945345 />
        <label for="cbb">945345 Blackberry</label>

        <input type="checkbox" name="cba" id="cba" value = 945345 />
        <label for="cba">945345 Android</label>

        <input type="checkbox" name="cbw" id="cbw" value = 945345 />
        <label for="cbw">945345 Windows Mobile</label>

        <input type="checkbox" name="cbo" id="cbo" value = 945345 />
        <label for="cbo">945345 All Other</label>

        </fieldset> 

</div>

The logic is when a user click on a checkbox, the checkbox value goes to a variable and again the user if clicks on another checkbox that value adds up into first value. Thanks in advance

2 Answers 2

4

Do you mean like:


var total = 0;
$("input[type='checkbox']").click(function() {
 //if you want to add on checked
 if($(this).is(":checked")) {
     var v = parseInt($(this).val(), 10);
     total += v;
 }
 else {
   total -= v;
 }
});

Hope it helps

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

Comments

1

You could do;

var tot = 0;

$("input:checkbox").click(function() {
  var val = parseInt(this.value, 10);
 if($(this).is(":checked")) {
     //add to total if it's checked
     tot += vale;
 }else{
     //this was previously checked, subtract it's value from total
     tot -= vale;
 }
});

Comments

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.