rodrix rodrix - 1 month ago 6
Javascript Question

Subtract 1 from total if check box is checked

Say you have a checkbox and beside it you show any numbers, be it 10 and when user clicks on the checkbox then that 10 becomes 9 but if unchecks then it again becomes 10.

<input type="checkbox" id="credits" name="credits" <?php echo $checked;?> /> (10) Credit


The value of credit would be fetched from database.

Answer

$(function () {
  $('#credits').change(function () {
    var currentValue = parseInt($('#credit-amount').text());
    var newValue = currentValue + ($(this).prop('checked') ? -1 : 1);
    $('#credit-amount').text(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="credits" name="credits" /> (<span id="credit-amount">10</span>) Credit