Retrive the Checkbox value and how to add the values of checkbox
Asked Answered
E

2

0

Need to get the values of checkbox and need to store in a single variable by adding all values instead of storing in array.how should i get it.?

here my fiddle and my jquery

function getCheck() {
         $('ul.addon > li :checked').each(function() {
           allVals.push($(this).val());
           });
            return allVals;
      }
     $(function() {
       $('ul.addon > li > input').click(getCheck);
       getCheck();
    $(allVals).each(function(){
        addon+=parseInt(allVals);
        $('#op').html(addon);
    });        
     });

here allvals array contain al the values of checked checkbox 1,2,1,1,3

Now i need to add those values and move into addon variable like 1+2+1+1+3=8

and if i uncheck the checkbox the value must be minused i tried my best i did' t able to get it.. :( thanks in advance

Ellary answered 8/10, 2013 at 9:39 Comment(0)
C
0

If you need to add and subtract the value of a checkbox on the checkbox click,try the code below.Hope this is what you meant.

var allVals = [];
$('input:checkbox[name=addons]').each(function() {
           allVals.push($(this).val());
 });//Gets the complete List of values

//Adds and subtracts the value on click

 var curr_value=0;
    $("input:checkbox[name=addons]").on('click',function() {
         if($(this).is(":checked") == false){
            curr_value = curr_value -$(this).val();

        }

         if($(this).is(":checked") == true){
            curr_value = curr_value + +$(this).val();
        }
        alert(curr_value);//Contains the added values of the checked boxes 

    });
Consensual answered 8/10, 2013 at 10:2 Comment(2)
live function showing this error TypeError: $(...).live is not a function.Ellary
try changin "live" to "on" as "live" is depreciated in the newest versions... :)Consensual
S
0

I hope i understand your question well enough, but you want to add the value when checked and minus the value when not checked? Try this:

var value = 0;

$('input[type="checkbox"]').change(function()
{
    if($(this).is(':checked'))
    {
        value += parseInt($(this).val());
    }
    else
    {
        value -= parseInt($(this).val());  
    }

    alert(value);
})

On status change of the checkbox i validate the status(checked or not checked). When checked i som the value else i will minus the value.

jsFiddle

Starry answered 8/10, 2013 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.