jquery - checkbox oncheck total will be updated

I was trying to develop a checkbox using jQuery ..where oncheck total will be updated but when i uncheck it will be back as it is.. Here total updated with oncheck but it don't get back to total amount when i uncheck it .what could be possible error..anyone help please?

$('#vat').on('click',function(e){
    var vat = document.getElementById("vat").value;
    var total = document.getElementById("total").value;

    var sum = +total + +vat;
     document.getElementById("total").value =  sum;
  });

1 answer

  • answered 2017-06-17 18:13 Mohamed-Yousef

    Assume #vat is your input id

    1- You need to use change instead of click for radio and checkbox inputs

    2- check if checked or not by using this.checked

    $('#vat').on('change',function(e){
        var sum = 0;
        var vat = document.getElementById("vat").value;
        var total = document.getElementById("total").value;
        if(this.checked === true){
           sum = total + vat;
        }else{
           sum = total - vat;
        }   
         document.getElementById("total").value =  sum;
      });
    

    And while you're using and tagged jquery

       $('#vat').on('change',function(e){
            var sum = 0;
            var vat = parseInt($(this).val());
            var total = parseInt($("#total").val());
            if(this.checked === true){
               sum = total + vat;
            }else{
               sum = total - vat;
            }   
             $("#total").val(sum);
        });