javascript 复选框选中事件的javascript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9479777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:48:32  来源:igfitidea点击:

javascript function for checkbox checked event

javascriptjqueryjquery-mobile

提问by h_a86

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

我需要一个可以在单击事件上添加复选框值的函数。我的 html 代码是

<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

逻辑是当用户单击复选框时,复选框值转到变量,如果用户单击另一个复选框,则该值加起来为第一个值。提前致谢

回答by Sudhir Bastakoti

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

希望能帮助到你

回答by Nicola Peluchetti

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