Search code examples
javascriptjquerycheckboxternary

Use checkbox in jQuery to toggle 2 numeric values


How would I alter the below code to toggle between a non zero value and a zero value when checkbox is checked and unchecked? See

$(document).ready(function() {
  $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
  });
});
.box {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label><input type="checkbox" name="colorCheckbox" value="n1"> num 1</label>
  <label><input type="checkbox" name="colorCheckbox" value="n2"> num 2</label>
  <label><input type="checkbox" name="colorCheckbox" value="n3"> num 3</label>
</div>
<div class="n1 box">55000</div>
<div class="n2 box">200</div>
<div class="n3 box">300</div>

https://jsfiddle.net/hcanning/53ye8wf7/


Solution

  • You can do it like this, to get sum for each checkbox, tweaked as you need

    $(document).ready(function() {
    var sum = 0;
      $('input[type="checkbox"]').change(function() {
        var inputValue = $(this).attr("value");
    
       if(this.checked) {
           sum = parseInt(sum) + parseInt($("." + inputValue).text());
       }else {
           sum = parseInt(sum) - parseInt($("." + inputValue).text());
        }
        $("#sum").text(sum);
    
        $("." + inputValue).toggle();
      });
    });
    .box {
      display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
       
    
    
    <table width="100%">
    <tr> 
    <td> <label><input type="checkbox" name="colorCheckbox" value="n1"> Show Price</label></td><td><div class="n1 box">55000</div></td>
    </tr><tr> 
    <td> <label><input type="checkbox" name="colorCheckbox" value="n2"> Show Price</label></td><td><div class="n2 box">200</div></td>
    </tr><tr> 
    <td> <label><input type="checkbox" name="colorCheckbox" value="n3"> Show Price</label></td><td><div class="n3 box">300</div></td>
    </tr>
    
    <tr> 
    <td > Total: </td><td><div id="sum">0</div></td>
    </tr>