bma pachuau bma pachuau - 4 months ago 14
jQuery Question

Calculate discount using jquery

I am calculating Discount using jquery. But I have a problem calculating the correct discount. My calculation gives me wrong result.

Here is my code



$(document).on("change keyup blur", "#chDiscount", function() {
var amd = $('#cBalance').val();
var disc = $('#chDiscount').val();
if (disc != '' && amd != '')
$('#cBalance').val((parseInt(amd)) - (parseInt(disc)));

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">





I have a prepopulated value for
cBalance
input i.e.,
1575
. When I type discount value for example 500 in
chDiscount
input, it gives me
1020
and not 1075. And I want the value
1575
to be
1575
when there is no value or zero value in the
chDiscount
input. And the caculation keeps incrementing the cBalance value whenever I type new value in the chDiscount input, it does not increment from the default value.
My exptected output: When I type 500, I want the default value 1575 to be 1075. And if I delete the 1000 that I type, I want back the default value 1575 in cBalance. And If I type 5 in chDiscount, the default value would become 1570 and if I hit backspace to delete, it would become 1575 again.
How can I achieve this? Where did I go wrong? Please help.

Answer

$(document).on("change keyup blur", "#chDiscount", function() {
  var amd = $('#cBalance').val();
  var disc = $('#chDiscount').val();
  if (disc != '' && amd != '') {
    $('#result').val((parseInt(amd)) - (parseInt(disc)));
  }else{
    $('#result').val(parseInt(amd));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">
<br>
<input type="number" id="result">

I added result field because otherwise you couldn't specify amd