复选框已选中按钮的更改值(计数)

时间:2019-01-10 11:10:05

标签: javascript jquery

我有一些带有数字值的复选框,当选中一个或多个chceckbox时,需要在按钮括号中显示计数结果: 我找到并编辑了这段代码;

$('input:checkbox').on('change', function(){
    $('#count').html($('input:checkbox:checked').size());
});

$('button').text('Price is () Euro');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox">Price 10 Euro</label>
<label><input type="checkbox">Price 25 Euro</label>
<label><input type="checkbox">Price 30 Euro</label>

<button id="count">Price is () Euro</button>

1 个答案:

答案 0 :(得分:2)

这可以做到

var count=0;
$('input:checkbox').on('change', function(){
    if($(this).is(':checked'))
    count+=Number($(this).val());
    else
    count-=Number($(this).val());
    $('button').text('Price is ('+count+') Euro');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <label><input type="checkbox" value=10>Price 10 Euro</label>
        <label><input type="checkbox" value=25>Price 25 Euro</label>
        <label><input type="checkbox" value=30>Price 30 Euro</label>
        
        <button>Price is () Euro</button>
      
</body>
</html>