首页 > 解决方案 > 复选框被选中更改按钮的值(计数)

问题描述

我有一些具有其数值的复选框,并且需要在选中一个或多个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>

标签: javascriptjquery

解决方案


这会做-

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>


推荐阅读