Retrive the Checkbox value and how to add the values of checkbox

淺唱寂寞╮ 提交于 2019-12-14 03:03:52

问题


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


回答1:


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 

    });



回答2:


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



来源:https://stackoverflow.com/questions/19244177/retrive-the-checkbox-value-and-how-to-add-the-values-of-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!