简体   繁体   English

在JQuery中,如何将“已检查”复选框的所有值加在一起?

[英]In JQuery, how do I add all the values of “checked” checkboxes together?

<input type="checkbox" class="new_message" value="1">
<input type="checkbox" class="new_message" value="2"  checked="checked">
<input type="checkbox" class="new_message" value="4" checked="checked">



total_score = $("input.new_message").checked.each(function(){
    ...? 
});

The total score should be 6. I want to add all the checked values up of the same class. 总分应为6。我想将同一类的所有检查值加起来。

you can do something like this 你可以做这样的事情

var total_score = function () {
      var x = 0 ;
        $("input.new_message:checked").each(function(){
       x +=  Number($(this).val());
      });

    return x ; 

  }

DEMO 演示

Start a counter, then increment it on each pass. 启动一个计数器,然后在每次通过时将其递增。 $.each won't return anything. $.each都不会返回任何东西。

var total_score = 0;
$("input.new_message:checked").each(function(){
    total_score += parseInt($(this).val());
});

Something like this : 像这样的东西:

var total_score = 0;

$('input.new_message:checked').each(function(){
    total_score += Number($(this).val());
});
 var sum = 0; 

$("input.new_message").each(function(){
    if($(this).prop(checked)){
    sum += $(this).val(); 
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM