h_a86
h_a86

Reputation: 772

javascript function for checkbox checked event

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

Upvotes: 3

Views: 10148

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

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

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

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

Upvotes: 4

Related Questions